【问题标题】:Laravel Eloquent - building 'where not' query with relationshipLaravel Eloquent - 用关系构建“哪里不是”查询
【发布时间】:2018-12-04 04:03:48
【问题描述】:

我有 5 个具有相同 client_id 的数据库行,3 个标记为 completed, Yes

此代码按预期提取 3 个结果:

$indGoal = $client->indGoal()->where('completed','=','Yes')->get();

这段代码没有结果:我希望是 2。

$indGoal = $client->indGoal()->where('completed','!=','Yes')->get();

This question 建议添加 ->orWhereNull('completed') - 这有效,但忽略了 client_id 关系。请求带来所有非Yes 的结果,不管$client

我的客户模型供参考:

public function indGoal()
{
    return $this->hasMany('App\Models\IndGoal');
}

【问题讨论】:

    标签: php laravel eloquent


    【解决方案1】:

    您应该将 orWhere 过滤器分组到回调中,这样它们就不会干扰现有的过滤器。

    $indGoal = $client->indGoal()
        ->where(function ($query) {
            $query->orWhere('completed', '!=', 'yes')
                ->orWhereNull('completed');
        })
        ->get();
    

    这样,查询生成器知道任何分组条件都应该为真,而所有其他条件都是独立的。

    【讨论】:

    • 这行得通,谢谢!我不明白为什么它会起作用 - 为什么首先需要 whereNull?
    猜你喜欢
    • 2020-11-02
    • 2013-10-03
    • 2017-07-19
    • 2018-02-07
    • 2021-09-25
    • 2015-01-21
    • 2017-01-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多