Laravel:获取特定于多对多关系的数据透视 [英] Laravel: Get pivot data for specific many to many relation
问题描述
我的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
我该如何实现?
推荐答案
在User
和Target
的关系上,添加->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屋!