Laravel:获取特定多对多关系的枢轴数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27434338/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 16:49:42  来源:igfitidea点击:

Laravel: Get pivot data for specific many to many relation

laravelrelationship

提问by Strernd

My Usermodel has many Targetand vice versa. Now I've got a given Userand given Targetand I want to access pivot data from their relation. The pivot column is called type

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

How can I achieve this?

我怎样才能做到这一点?

回答by maknz

On the relationships for both Userand 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.

在两者的关系UserTarget上,粘性->withPivot('type')将指示Laravel包括该列。然后,一旦获得结果集,就可以使用$user->pivot->type.

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

如果你不是遍历一个集合,但有一个用户和他们的目标之一,并希望type现场,你可以使用$target = $user->targets->find($targetId)和访问与类型$target->pivot->type

More at http://laravel.com/docs/4.2/eloquent#working-with-pivot-tables

更多信息请访问http://laravel.com/docs/4.2/eloquent#working-with-pivot-tables