Php Laravel:检查特定列透视表
我有一个多对多关系,表上有一个附加值列。如何选择该值?所以Php Laravel:检查特定列透视表,php,laravel-4,Php,Laravel 4,我有一个多对多关系,表上有一个附加值列。如何选择该值?所以 pivot_table - user_id - something_id - value 型号用户: return $this->belongsToMany('Something', 'user_something')->withPivot('value'); 现在,我想得到一个用户的值,其中something id是2 大概是这样的: $user = User::find(1); $user->something
pivot_table
- user_id
- something_id
- value
型号用户
:
return $this->belongsToMany('Something', 'user_something')->withPivot('value');
现在,我想得到一个用户的值,其中something id是2
大概是这样的:
$user = User::find(1);
$user->something->whereSomethingId(2)->pivot->value;
你可以试试这个:
$user->something->find(2)->pivot->value;
由于something
是一个集合,因此我们可以使用find($id)
方法通过它的id
获取项目。此外,您还可以使用filter(callback)
方法使用循环过滤集合,并在每个循环中运行回调(作为参数传入filter
方法),例如:
$user->something->filter(function($item){
// $item is an object from the collection
// So, you may use: $item->pivot->value
});
你也可以阅读