[英]Laravel relationship is returning null
我想創建簡單的關系,以User
模型在數據庫中查找用戶的個人資料信息。
在User.php中,我有:
class User extends Eloquent implements UserInterface, RemindableInterface {
...
public function profile() {
return $this->hasOne('UserProfile');
}
...
}
並在model / UserProfile.php中:
class UserProfile extends Eloquent{
protected $table='user_profile';
public function user() {
return $this->belongsTo('User');
}
}
數據庫中的users.user_id
和user_profile.user_id
為1000
。
我想通過控制器中的此行訪問用戶個人資料:
public function getIndex()
{
$profile = $user->profile;
dd( $profile );
die;
}
dd()
結果是:
NULL
我的人際關系問題是什么?
好像沒有加載關系。
要么嘗試使用eager-loading加載它們
User::with('user_profile')->get();
或稍后通過延遲加載來加載它們:
$user = Auth::user();
$user->load('user_profile');
另外,由於您使用的是id
以外的另一個主鍵屬性,因此需要指定它(或在關系聲明中):
protected $primaryKey = 'user_id';
對於您的users
表,您使用的是與預期不同的id
以外的其他主鍵,因此在您的User
模型中,您應明確聲明protected $primaryKey = 'user_id'
,並且您也可以使用以下方法:
// Not tested with same foreign and local key
return $this->hasOne('UserProfile', 'user_id', 'user_id');
但是最好將兩個密鑰保持不同,可能您可以將users.user_id
重命名為users.id
。 如果重命名users.user_id
到users.id
那么一切都將不工作,在所有的任何更改。
我曾經遇到過同樣的問題,原因是該列后面有一個空白,可以用作關系。 只需刪除即可解決。 可能與您的問題沒有直接關系,但是我相信這可以節省一些通過搜索引擎訪問此頁面的人。
對我來說,解決方案急於加載,就像@zwacky建議的那樣:
或稍后通過延遲加載來加載它們:
>$user = Auth::user();
>$user->load('user_profile');
當剛剛創建了user_profile
並且您需要在代碼的另一部分中通過$user
訪問user_profile
時,這將解決該問題。 看起來laravel不會立即更新父模型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.