簡體   English   中英

Laravel Eloquent。 使用 With() 時,如何將數據傳遞給 Model?

[英]Laravel Eloquent. When using With(), how can I pass data to the Model?

我的數據庫結構是

輪廓

  • ID..

Profile_row

  • ID
  • 名稱:eks "First_name"
  • 內容:eks“詹姆斯”
  • Profile_id: 1

在我的 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM