亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Laravel Eloquent 'with' 返回 null,但引用對象本身的關系返回正確的值

Laravel Eloquent 'with' 返回 null,但引用對象本身的關系返回正確的值

PHP
蝴蝶刀刀 2022-12-23 15:09:24
如果能幫助我理解我在 laravel 6.8 項目中看到的以下差異,我將不勝感激:我有一個“UserAlert”模型class UserAlert extends Model{    /**     * The attributes that are mass assignable.     *     * @var array     */    protected $fillable = [        'user_id', 'from_id', 'subject', 'message'    ];    //Relationships    public function user()    {        return $this->belongsTo(User::class);    }    //Only include the name of the sender in this relationship    public function from()    {        return $this->hasOne(User::class, 'id', 'from_id')->select('name');    }}“用戶”關系是默認的“user_id”到“id”,并且按預期工作。如您所見,“來自”關系從與 UserAlert 的“from_id”關聯的用戶模型中提取名稱。如果我獲得 UserAlerts 的集合,然后對其進行迭代以獲取每個 UserAlerts 的“來源”關系,如下所示:$thisUserAlerts = \App\UserAlert::where('user_id', $thisUser->id)->get();foreach ($thisUserAlerts as $userAlert) {    dump($userAlert->from);}然后我確實按照我的意愿從“來自”關系中看到了名字:...#original: array:1 [    "name" => "Administrator"  ]...但是,如果我嘗試使用“with”將關系直接包含在 UserAlert 集合中,則“from”始終為空。$thisUserAlertsWith = \App\UserAlert::where('user_id', $thisUser->id)->with('from')->get();dump($thisUserAlertsWith);...#relations: array:1 [        "from" => null      ]...我可以從查詢日志中看到,當我執行上述操作時,沒有從用戶表中提取名稱的 sql 查詢,但是當我遍歷集合并直接調用“->from”時,就會進行查詢。我誤解了“與”嗎?[為清楚起見,編輯以消除示例中的差異]
查看完整描述

1 回答

?
森林海

TA貢獻2011條經驗 獲得超2個贊

對于要包含的關系,事實證明您必須在集合中包含主鍵 (id)。

所以第一個答案是修改關系

return $this->hasOne(User::class, 'id', 'from_id')->select('name');

return $this->hasOne(User::class, 'id', 'from_id')->select(['id', 'name']);

然后我的原始示例按預期工作。

對此進行研究也讓我想到了另一種選擇,即不限制關系本身的字段,而是在“with”調用中限制它們。

所以從關系中完全刪除選擇:

return $this->hasOne(User::class, 'id', 'from_id')

而是使用以下內容過濾集合:

$userAlerts =  UserAlert::where('user_id', $id)->with('from:id,name')->get();

同樣,您必須包含主鍵 (id) 才能正常工作。


查看完整回答
反對 回復 2022-12-23
  • 1 回答
  • 0 關注
  • 118 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號