【问题标题】:Laravel Eloquent. When using With(), how can I pass data to the Model?Laravel 雄辩。使用 With() 时,如何将数据传递给模型?
【发布时间】:2021-04-22 20:56:31
【问题描述】:

我的数据库结构是

个人资料

  • 身份证 ..

Profile_row

  • 身份证
  • 姓名:eks "First_name"
  • 内容:eks“詹姆斯”
  • Profile_id:1

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

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

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

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

我得到了一个包含配置文件的漂亮嵌套列表,以及 name=first_name 下的每个 profile_row。

但是如何将参数从控制器发送到模型,在模型中定义我想要返回的配置文件行“名称”?

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);
}

【问题讨论】:

    标签: php laravel eloquent laravel-7


    【解决方案1】:

    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

    【讨论】:

      猜你喜欢
      • 2018-09-02
      • 2017-11-05
      • 2021-08-11
      • 1970-01-01
      • 2018-07-05
      • 1970-01-01
      • 1970-01-01
      • 2015-08-15
      • 1970-01-01
      相关资源
      最近更新 更多