My db structure is
Profile
Profile_row
In my controller I do this:
$profiles = Profile::with('profile_row')->paginate($request->per_page);
and my Profile Model looks like this
public function profile_row()
{
return $this->hasMany('App\ProfileRow')->where('name', 'first_name');
}
And I get a nice nested list with profiles, and every profile_row where name=first_name under.
But how can I send a argument from the controller to the Model where I define what profile row 'name' I want to return?
Eks: Controller (This don't work, but I hope it will show what I'm after)
$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);
}
Alter you profile_row
model's method to be whithout the name
parameters:
public function profile_row()
{
return $this->hasMany('App\ProfileRow');
}
When you load relationship with the with
method add the constraint there.
$profiles = Profile::with(['profile_row'=>function($query) use($name)
{
$query->where('name', $name);
}])->paginate($request->per_page);
From the doc https://laravel.com/docs/8.x/eloquent-relationships#constraining-eager-loads
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.