[英]How to set value foreign key of foreign key Laravel
訪問Model
id
user_id
visit_date
public function user()
{
return $this->belongsTo(USER::class,'user_id','user_id')->withTrashed();
}
User Model
user_id
branch_id
name
public function branch()
{
return $this->belongsTo(BRANCH::class,'branch_id','branch_id')->withTrashed();
}
科 Model
branch_id
branch_desc
I want to display branch_desc when getting list of Visit.
目前我只顯示來自用戶 Model 的 branch_id
您需要從訪問用戶表和用戶到分支表建立一對多關系
前任。 關系代碼:
//From Visit to User model
$this->belongsTo(User::class, 'user_id')
//From User to Branch Model
$this-belongsTo(Branch::clas, 'branch_id')
這將允許您像這樣急切地加載 controller 中的關系
Visit::with(['user.branch'])
//Now you will get all visits with neseted users and branch
我會建議你看看 laravel 關系文檔,以便更好地理解Laravel 關系與預加載
對於 2 層(或更多)關系,我建議你從 Staudenmeir 安裝這個 package https://github.com/staudenmeir/eloquent-has-many-deep
在您的訪問 model 中,您可以添加如下關系:
public function branches() {
$query-> hasManyThrough(Branch::class, User::class);
}
有關更多信息,請查看與此相關的 LaravelDaily 教程 package https://youtu.be/wgdWokrm3Mw
你的問題真的不清楚。 但是,據我從您的問題中了解到,您還應該有一個分支 model 和遷移。
因此,從訪問表中,您將通過訪問 model 時與用戶的關系獲取用戶。
public function user()
{
return $this->belongsTo(User::class, 'id', 'user_id');
}
然后,當您可以通過您與 Branch 的用戶關系從您的用戶 model 獲取您的用戶分支時。
public function branch()
{
return $this->hasMany(Branch::class, 'user_id', 'id');
}
因此,您將像這樣獲取數據:
$visit->user->branch->description
您可以將描述替換為任何 column_name_that_wish_to_fetch。
SOLVED!!!
Use this in getting list of your model in Controller. This is how to query with multiple relationship
$visit= VISIT::with('USER.BRANCH')->orderBy('user_id','desc');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.