我的应用程序中有一种关系,一个组织可以有很多用户,很多用户可以有很多组织,在我的模型中,这看起来像这样,
组织.php
public function users() {
return $this->belongsToMany('User')->withPivot('is_admin');
}
用户.php
public function organisations() {
$this->belongsToMany('Organisation');
}
我想做的是运行一个具有多个where子句的查询,然后返回行数据和任何透视数据。
对于其中一个条款,我会做以下,
$org = Organisation::find(1);
$orgUsers = $org->users()
;
我想不出的是,如果我也需要的话,我将如何使用多个where?
假设您想将wheree()
添加到用户中,它可能看起来像这样(急切地加载用户)
$constraints = ['fname' => 'john', 'lanme' => 'doe'];
$org = Organisation::with(['users' => function($query) use ($constraints){
foreach($constraints as $field => $val)
$query->where($field, $val);
// Or if you just want admin users using your pivot table field
$query->pivot->where('is_admin', true);
}])->find($id);
或者,如果你需要一个用户集合和一个管理员集合,你可以获得所有的,并过滤它们
$org = Organisation::with('users')->find($id);
$admins = $org->users->filter(function($user){ return $user->pivot->is_admin });