Laravel:获取特定于多对多关系的数据透视 [英] Laravel: Get pivot data for specific many to many relation

查看:95
本文介绍了Laravel:获取特定于多对多关系的数据透视的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的User模型有很多Target,反之亦然. 现在,我有一个给定的User和给定的Target,我想从它们的关系中访问数据透视.枢轴列称为type

My User model has many Target and vice versa. Now I've got a given User and given Target and I want to access pivot data from their relation. The pivot column is called type

我该如何实现?

推荐答案

UserTarget的关系上,添加->withPivot('type'),这将指示Laravel包括该列.然后,设置好结果集后,即可使用$user->pivot->type访问该字段.

On the relationships for both User and Target, tack on a ->withPivot('type') which will instruct Laravel to include that column. Then once you have your result set, you can access the field with $user->pivot->type.

如果您不遍历集合,但是有一个用户和他们的目标之一,并且想要type字段,则可以使用$target = $user->targets->find($targetId)并通过$target->pivot->type访问类型.

If you're not iterating over a collection, but have a user and one of their targets and want the type field, you could use $target = $user->targets->find($targetId) and access the type with $target->pivot->type.

更多信息,请参见 http://laravel.com/docs/4.2/eloquent#working-with -数据透视表

这篇关于Laravel:获取特定于多对多关系的数据透视的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆