php - Laravel 使用多个 where 子句选择数据并返回任何数据透视表数据

标签 php mysql database laravel eloquent

我的应用程序中有一种关系,一个组织可以拥有许多用户,许多用户可以拥有许多组织,在我的模型中,它看起来像这样,

组织.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/

相关文章:

php - 尝试根据名称将 CSV 加载到 MySql 表中

php - Abs() - PHP 中的绝对值函数问题

java - 我应该如何编辑 jar 的 list ?

php - 如何将数组插入mysql数据库?

php - Codeigniter 首次使用者

javascript - 获取复选框的值并执行计算

php - 创建电影调查 - PHP 问题

php - undefined variable mysql-php

java - 如何将其保存到 parse.com 数据库?

python - 使用脚本语言动态数据库