[英]laravel how I can access data of model through another model
我正在使用 laravel 8 並且我具有以下表結構。
id,name,email,password,...等。
id,bio,facebook,twitter,phone,user_id,...等。
id, title, details, image, user_id,....等。
我在項目 model 中創建了以下關系
public function user(){
return $this->belongsTo(User::class,'user_id');
}
並且在用戶 model 中有另一個關系如下
public function profile(){
return $this->hasOne(UserProfile::class,'user_id');
}
我的問題是如何通過項目 model 訪問用戶配置文件? 我閱讀了 hasOneThrough 關系,但我不明白如何在我的代碼中應用它
首先,您需要獲得一個用戶,然后您才能訪問該配置文件。 所以:
Project::with('user.profile')->get()
假設在您的user_profiles
表中您有project_id
作為外鍵,請嘗試:
public function userProfile()
{
return $this->hasOneThrough(
UserProfile::class,
Project::class,
'user_id', // Foreign key on the projects table
'project_id', // Foreign key on the user_profiles table
'id', // Local key on the users table
'id' // Local key on the projects table
);
}
改變這個:
public function profile(){
return $this->hasOne(UserProfile::class,'user_id');
}
對此:
public function profile(){
return $this->belongsTo(UserProfile::class,'user_id');
}
將此添加到您的用戶配置文件 model 中:
public function user(){
return $this->hasOne(User::class);
}
獲取項目並嘗試檢查是否有效:
$project->user->profile;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.