【发布时间】:2020-09-23 12:34:32
【问题描述】:
我认为这会很简单,但目前还没有打球。
我有 2 个表来回答这个问题,“applications”和“application_call_logs”。
此查询需要从应用程序表中返回所有最新调用日志的状态不为 X。
这是当前查询:
$query = Application::query();
$query->where(function($query) {
$query->whereDoesntHave('call_logs');
$query->orWhereHas('latest_call_log', function($q) {
$q->where('status', '!=', 'not interested');
});
});
return $query->get();
这应该返回所有没有呼叫日志的行,或者最新的呼叫日志没有等于特定字符串的状态字段。
这里是:
$q->where('status', '!=', 'not interested');
如果 call_logs 有超过 1 行,似乎没有影响,即使我正在查询最新的关系。我还验证了 latest 正在返回正确的最新记录。
Application 模型中的两种关系是:
public function call_logs()
{
return $this->hasMany('App\ApplicationCallLog', 'lead_id', 'id');
}
public function latest_call_log()
{
return $this->hasOne('App\ApplicationCallLog', 'lead_id', 'id')->latest();
}
检查生成的 SQL:
select * from `applications` where (not exists (select * from `lead_call_logs` where `applications`.`id` = `lead_call_logs`.`lead_id`) or exists (select * from `lead_call_logs` where `applications`.`id` = `lead_call_logs`.`lead_id` and `status` != ?))
【问题讨论】:
-
检查生成的 SQL 或许是个好主意?
-
@onlineThomas 好声音,刚刚更新了问题,我也看了一下。