【问题标题】:How to retrieve the model linked to a many to many relation in Laravel?如何在 Laravel 中检索链接到多对多关系的模型?
【发布时间】:2017-05-23 14:31:00
【问题描述】:

我有三个模型:Wall、Post 和 Constraint。他们都有一个身份证。

Post
id

Wall
id

Constraint
id

Post_wall
post_id
wall_id
constraint_id

在 Wall 和 Post 之间,我有一个 ManyToMany 关系。在该关系的数据透视表中,我有一列 constraint_id。当我检索所有链接到墙的帖子时,我还需要数据透视表中链接的约束。

现在我可以使用 withPivot('constraint_id') 方法获取 constraint_id。

return $this->belongsToMany('App\Wall')
       ->withPivot('constraint_id')

但我想要的是对象,而不是 id。这在 Laravel 中可行吗?

return $this->belongsToMany('App\Wall')
       ->withPivot('constraint_id')
       ->join('constraints', 'post_wall.constraint_id', '=', 'constraint.id');

我也尝试加入约束表,但它没有返回对象。

【问题讨论】:

  • 到目前为止你尝试了什么?
  • 查看这个链接,我想你可以在这里找到答案:easylaravelbook.com/blog/2016/04/06/…
  • 在您链接的页面末尾,我找到了 ->withPivot('description') 方法。这将返回描述。在我的情况下,这会将约束 ID 放在 Post 对象中,但我希望将 Constraint 对象放在 Post 对象中,而不仅仅是 id。
  • 一种选择是当您从数据透视表中以Constraint::find($constraint_id) 获得constraint_id 时查询Constraint 模型。
  • 考虑过那个选项,但是在所有 post 对象中设置约束对象的 foreach 感觉不是很好。你应该认为 Laravel 会有更好的方法。

标签: php mysql database laravel model


【解决方案1】:
猜你喜欢
  • 2017-05-25
  • 2019-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多