Laravel Eloquent。使用 With() 时,如何将数据传递给模型?

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

我的数据库结构是

简介

Profile_row

在我的控制器中我这样做:

$profiles = Profile::with('profile_row')->paginate($request->per_page);

我的个人资料模型看起来像这样

public function profile_row()
{
    return $this->hasMany('App\ProfileRow')->where('name', 'first_name');
}

我得到了一个很好的嵌套列表,里面有配置文件,每个 profile_row where name=first_name under.

但是我如何才能将参数从控制器发送到模型,在模型中定义我想要 return 的配置文件行 'name'?

Eks:控制器(这不起作用,但我希望它能显示我所追求的)

 $profiles = Profile::with('profile_row('first_name')')->paginate($request->per_page);

型号:

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