sql - Eloquent:检查关系是否有一定的条件
问题描述
我有一个Survey
与另一个模型相关hasOne
的模型,该模型与另一个模型Installation
相关。所以我定义了这样的关系hasMany
Assignment
hasManyThrough
public function assignments()
{
return $this->hasManyThrough(Assignment::class,Installation::class);
}
我想编写一个查询来获取与调查相关联的任何Survey
地方Assignments
没有 assignment.type 0、1、2、3 和 4。
即每项调查应有 5 个任务和记录
Survey => [
[Assignment => [type = 0]]
[Assignment => [type = 1]]
[Assignment => [type = 2]]
[Assignment => [type = 3]]
[Assignment => [type = 4]]
]
我试过这个查询
$schedulables = Survey::whereNotNull('installer_id')
->where(function ($query) {
$query
->whereNotExists(function ($query) {
return $query->raw('SELECT * FROM assignments,installations where assignments.installation_id = installations.id and installations.survey_id = surveys.id and assignments.type= 1');
})
->orwhereNotExists(function ($query) {
return $query->raw('SELECT * FROM assignments,installations where assignments.installation_id = installations.id and installations.survey_id = surveys.id and assignments.type= 2');
})
->orwhereNotExists(function ($query) {
return $query->raw('SELECT * FROM assignments,installations where assignments.installation_id = installations.id and installations.survey_id = surveys.id and assignments.type= 3');
})
->orwhereNotExists(function ($query) {
return $query->raw('SELECT * FROM assignments,installations where assignments.installation_id = installations.id and installations.survey_id = surveys.id and assignments.type= 4');
});
})
->with('customer', 'installer', 'installation')
->latest('updated_at')->get();
请任何建议和帮助将不胜感激。
解决方案
如果我正确理解了您的问题,您可以使用whereHas()和whereNotIn()来实现您的目标:
$schedulables = Survey
::with('customer', 'installer', 'installation')
->whereNotNull('installer_id')
->whereHas('assignments', function ($query) {
$query->whereNotIn('type', [0, 1, 2, 3, 4]);
})
->latest('updated_at')
->get();
推荐阅读
- css - 打印时 Bootstrap 4 响应式表格中断
- javascript - 根据 jQuery 下拉列表中的数字选择添加输入字段
- c - Stm32f4 发现中断与 RAM 中的程序
- r - ggplot - 形状和颜色由变量决定的 geom_point,其中颜色来自自定义调色板
- c++ - opencv::dnn 中的神经网络输入大小
- reactjs - 如何根据父/子关系排序评论
- c# - DocumentClient 在 Azure-CosmosDB 中返回单个对象
- css - 如何防止 SVG 背景图像缩放?
- r - Innerjoin 导致 R 中的 tibble 为空
- arrays - 如何使用 numpy 生成具有动态大小的数组数组?