duanboshi1472
2014-04-03 14:30
浏览 36
已采纳

Laravel:检查特定列数据透视表

I have a Many-to-Many relationship where there is an addional value column on the table. How do I pick that value? So...

pivot_table
- user_id
- something_id
- value

Model User:

return $this->belongsToMany('Something', 'user_something')->withPivot('value');

Now, I would like to get the value for one user where the something id is 2.

Something like this:

$user = User::find(1);
$user->something->whereSomethingId(2)->pivot->value;
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doulei6778 2014-04-03 16:01
    已采纳

    You may try this:

    $user->something->find(2)->pivot->value;
    

    Since something is a collection so we may use find($id) method to get an item by it's id. Also, you may use filter(callback) method to filter the collection using a loop and running the callback (passed in filter method as argument) in every loop, for example:

    $user->something->filter(function($item){
        // $item is an object from the collection
        // So, you may use: $item->pivot->value
    });
    

    You may also read this article.

    打赏 评论

相关推荐 更多相似问题