我的应用程序中有一种关系,一个组织可以拥有许多用户,许多用户可以拥有许多组织,在我的模型中,它看起来像这样,
组织.php
public function users() {
return $this->belongsToMany('User')->withPivot('is_admin');
}
用户.php
public function organisations() {
$this->belongsToMany('Organisation');
}
我想要做的是运行一个具有多个 where 子句的查询,然后返回行数据和任何数据透视数据。
对于一个 where 子句,我将执行以下操作,
$org = 组织::find(1);
$orgUsers = $org->users()
;
我不明白的是,如果我也需要的话,我将如何使用多个位置?
最佳答案
假设您想将 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 });
关于php - Laravel 使用多个 where 子句选择数据并返回任何数据透视表数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26426990/