![](/img/trans.png)
[英]Laravel Multi BelongsTo RelationShip Merge with Eager Loading
[英]Laravel 6 eager loading using with() on a belongsTo relationship is only *sometimes* returning null
我正在做一個項目,我們有一個 model 用於服務提供商,提供的護理類型和狀態:
提供者:
class Provider extends Model
{
protected $table = 'providers';
public function status() {
return $this->belongsTo('App\Status');
}
public function caretype() {
return $this->belongsTo('App\CareType', 'id');
}
}
護理類型:
class CareType extends Model
{
protected $table = 'type_of_care';
public function providers() {
return $this->hasMany('App\Providers', 'type_of_care_id');
}
public function category() {
return $this->belongsTo('App\CareCategory');
}
}
地位:
class Status extends Model
{
protected $table = 'status';
public function providers() {
return $this->hasMany('App\Providers');
}
}
在我的SearchController
(處理提供者搜索請求的 controller)上,使用預加載的show()
function 可以完美地檢索caretype
。 但是在列出搜索結果集合的search()
function 中, caretype
始終列為 null。
我不明白為什么它會在一個 function 而不是另一個中工作,特別是當兩個函數中的預加載代碼完全相同時:
public function search(Request $request)
{
$validated = $request->validate([
//I removed the validation code for this post
]);
$providers = Provider::with(['status', 'caretype'])->get();
return view('search.results', ['providers' => $providers]);
}
public function show($id)
{
$single_provider = Provider::with(['status', 'caretype'])->where('id', $id)->first();
return view('search.details', ['provider' => $single_provider]);
}
對此的任何幫助將不勝感激。 我知道 model 和關系外鍵已正確定義,因為show()
caretype
能夠很好地獲得護理類型。
不。 您的關系和外鍵不正確。 從文檔
Eloquent 通過檢查關系方法的名稱並在方法名稱后加一個
_
后跟主鍵列的名稱來確定默認外鍵名稱。 但是,如果 Child model 上的外鍵不是這樣,您可以將自定義鍵名稱作為第二個參數傳遞給 belongsTo 方法。
您將id
列作為Provider
模型的caretype
中的外鍵傳遞,但您的外鍵是type_of_care_id
。 所以當 id 匹配時你會得到一些結果,但如果不匹配,你會得到 null。 將您的關系代碼更改為
public function caretype()
{
return $this->belongsTo('App\CareType', 'type_of_care_id');
}
現在再次來自文檔
如果您的父 model 不使用
id
作為其主鍵,或者您希望將子 model 加入不同的列,您可以將第三個參數傳遞給指定父表的自定義鍵的belongsTo
方法。
在您的情況下, id
是主鍵。 所以你不必傳遞第三個參數。 只需更新主鍵引用,一切都會完美運行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.