[英]Laravel: Checking Specific Column Pivot Table
我有一个多对多关系,在表上有一个附加值列。 如何选择该值? 所以...
pivot_table
- user_id
- something_id
- value
模型User
:
return $this->belongsToMany('Something', 'user_something')->withPivot('value');
现在,我想获取某用户的东西,其中物ID为2。
像这样:
$user = User::find(1);
$user->something->whereSomethingId(2)->pivot->value;
您可以尝试以下方法:
$user->something->find(2)->pivot->value;
由于something
是一个集合,因此我们可以使用find($id)
方法通过它的id
获得something
。 另外,您可以使用filter(callback)
方法通过循环过滤集合,并在每个循环中运行回调(作为参数传递给filter
方法),例如:
$user->something->filter(function($item){
// $item is an object from the collection
// So, you may use: $item->pivot->value
});
您也可以阅读本文 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.