【发布时间】:2021-11-13 16:21:12
【问题描述】:
我有一个模型 Survey 与 hasOne 相关,另一个模型 Installation 与 hasMany 另一个模型 Assignment 相关。
所以我定义了一个像这样的hasManyThrough 关系
public function assignments()
{
return $this->hasManyThrough(Assignment::class,Installation::class);
}
我想编写一个查询来获取与调查关联的 Assignments 的 assignment.type 不为 0、1、2、3 和 4 的任何 Survey。
即 每个调查应该有 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();
如有任何建议和帮助,我们将不胜感激。
【问题讨论】:
标签: sql laravel eloquent laravel-query-builder