我正在尝试使用急切加载优化关系并在with子句中实现条件以进行预先加载,但是当我执行以下操作时:
$totalOpenQry = Enquiry::whereIn('staff_id', $employeeIds)
->with(['enquiryStats' => function ($query) {
$query->where('is_open','=',true)
->where('is_dead','=',false)
->orderBy('id','asc');
}])
->where('ed_timestamp', '>=', $dateRange['start'])
->with('country');
$totalOpen = $totalOpenQry->toSql();
$ totalOpenQry-> toSql()
产生以下内容:
'select * from `enquiries` where `staff_id` in (10, 15) and `ed_timestamp` >= '2017-09-12';
似乎忽略了我的with子句中的where条件。有没有办法解决这个问题或正确实施?
由于
答案 0 :(得分:2)
whereHas()
与has()
基本相同,但允许您为要检查的相关模型指定其他过滤器。
$totalOpenQry = Enquiry::whereIn('staff_id', $employeeIds)
->with('enquiryStats')
->whereHas('enquiryStats', function ($query) {
$query->where('is_open','=',true)
->where('is_dead','=',false)
->orderBy('id','asc');
})
->where('ed_timestamp', '>=', $dateRange['start'])
->with('country');
// only enquiryStats that have is_open = true and is_dead = false are returned
答案 1 :(得分:1)
您将获得2个查询:
1: 'select * from `enquiries` where `staff_id` in (10, 15) and `ed_timestamp` >= '2017-09-12';
2 Something like: 'select * from `stats` where `staff_id` in (10, 15) AND `is_open`=true...;
但->toSql()
仅显示。