首页 > 解决方案 > Laravel Eloquent - 用关系构建“哪里不是”查询

问题描述

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

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

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

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

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

这个问题建议添加->orWhereNull('completed')- 这有效,但忽略了这种client_id关系。该请求带来了所有非Yes结果,无论$client

我的客户模型供参考:

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

标签: phplaraveleloquent

解决方案


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

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

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


推荐阅读