[英]Laravel Eloquent. When using With(), how can I pass data to the Model?
我的數據庫結構是
輪廓
Profile_row
在我的 controller 我這樣做:
$profiles = Profile::with('profile_row')->paginate($request->per_page);
我的個人資料 Model 看起來像這樣
public function profile_row()
{
return $this->hasMany('App\ProfileRow')->where('name', 'first_name');
}
我得到了一個很好的嵌套列表,其中包含配置文件,以及 name=first_name 下的每個 profile_row。
但是,如何將參數從 controller 發送到 Model,在其中定義要返回的配置文件行“名稱”?
Eks:Controller(這不起作用,但我希望它會顯示我所追求的)
$profiles = Profile::with('profile_row('first_name')')->paginate($request->per_page);
Model:
public function profile_row($name)
{
return $this->hasMany('App\ProfileRow')->where('name', $name);
}
將您的profile_row
模型的方法更改為沒有name
參數:
public function profile_row()
{
return $this->hasMany('App\ProfileRow');
}
當您使用with
方法加載關系時,在此處添加約束。
$profiles = Profile::with(['profile_row'=>function($query) use($name)
{
$query->where('name', $name);
}])->paginate($request->per_page);
來自文檔https://laravel.com/docs/8.x/eloquent-relationships#constraining-eager-loads
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.