如何在Laravel中检索链接到多对多关系的模型?

时间:2017-01-09 10:43:30

标签: php mysql database laravel model

我有三种模式:Wall,Post和Constraint。他们都有身份证。

 Session session = getSession();
 Entity object = (Entity)session.load(Entity.class, new Integer(1));

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

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

Post
id

Wall
id

Constraint
id

Post_wall
post_id
wall_id
constraint_id

但我想要的是对象,而不是id。 Laravel有可能吗?

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

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

1 个答案:

答案 0 :(得分:4)

我认为您需要的是“检索中间表列”#39;有关此问题的详细信息,请访问https://laracasts.com/discuss/channels/eloquent/how-to-access-data-of-a-pivot-tablehttps://laravel.com/docs/5.1/eloquent-relationships#many-to-many