Laravel: Get pivot data for specific many to many relation

前端 未结 2 967
-上瘾入骨i
-上瘾入骨i 2020-12-03 02:44

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

相关标签:
2条回答
  • 2020-12-03 02:56

    You can also limit columns by passing array as 2nd arg to simplePaginate

    $query->users()->simplePaginate($per_page, ['users.id', 'users.email']);
    
    0 讨论(0)
  • 2020-12-03 03:19

    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

    0 讨论(0)
提交回复
热议问题