Laravel: Get pivot data for specific many to many relation

二次信任 提交于 2019-12-17 16:18:38

问题


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

How can I achieve this?


回答1:


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.

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.

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



来源:https://stackoverflow.com/questions/27434338/laravel-get-pivot-data-for-specific-many-to-many-relation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!