【问题标题】:Laravel selecting data with multiple where clauses and returning any pivot dataLaravel 选择具有多个 where 子句的数据并返回任何枢轴数据
【发布时间】:2014-10-17 14:13:52
【问题描述】:

我的应用中有一个关系,一个组织可以有很多用户,很多用户可以有很多组织,在我的模型中,这看起来像这样,

组织.php

public function users() {
    return $this->belongsToMany('User')->withPivot('is_admin');
}

用户.php

public function organisations() {
        $this->belongsToMany('Organisation');
}

我想要做的是运行一个包含多个 where 子句的查询,然后返回行数据和任何数据透视数据。

对于一个 where 子句,我会执行以下操作,

$org = Organisation::find(1);
$orgUsers = $org->users();

我想不通的是,如果我也需要,我将如何使用多个 where?

【问题讨论】:

  • 我在这里并没有真正得到你想要的东西。而且您的代码甚至无效(您忘记了 return $this->belongsToMany('Organisation')$org->users()->get()$org->users。您想将多个 where 子句应用于组织,然后获取其用户?或者您想要它的用户,但对其应用其他 where 子句?

标签: php mysql database laravel eloquent


【解决方案1】:

假设您想将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 });

【讨论】:

    猜你喜欢
    • 2020-05-08
    • 1970-01-01
    • 2021-07-30
    • 2018-05-19
    • 2020-12-27
    • 2018-11-12
    • 2019-11-11
    • 2013-01-07
    • 1970-01-01
    相关资源
    最近更新 更多