php - 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');
}
解决方案
您应该orWhere
在回调中对过滤器进行分组,这样它们就不会干扰现有的过滤器。
$indGoal = $client->indGoal()
->where(function ($query) {
$query->orWhere('completed', '!=', 'yes')
->orWhereNull('completed');
})
->get();
这样,查询生成器就知道任何分组条件都应该为真,而所有其他条件都是独立的。
推荐阅读
- jenkins - Jenkins Pipepline 失败:从 XXX 对 JNLP4-connect 连接的远程调用失败
- php - 在 null 上调用成员函数 comments()
- android - 我可以通过在 Oreo 及更高版本的服务中动态注册 ACTION_PACKAGE_ADDED 广播来使用前台服务来监视新应用程序的安装吗
- typescript - 打字稿:compilerOptions.outDir 和非 ts 模块
- laravel - 如何在 laravel 的自定义类中使用队列?
- c# - 如何将大型项目列表视图呈现为 RenderTargetBitmap?
- javascript - 使用检查元素上传图像
- sql - SQL groupby 将唯一的字符串组合成一个字符串
- postgresql - ConverterNotFoundException:从类型 [java.math.BigDecimal] 到类型 [com.spacestudy.model.DeptListForJointusePer]
- android - 从 RN 应用程序共享时,无法在 Android 上显示 % 符号