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('AppModelsIndGoal');
}

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

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

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

最新更新