我使用Eloquent编写了以下查询:
Contact::select(DB::raw("DATE_FORMAT(DATE(`created_at`),'%b %d') as date"))
->addSelect(DB::raw("`created_at`"))
->addSelect(DB::raw("COUNT(*) as `count`"))
->where('created_at', '>', $date)
->ofType($type)
->groupBy('date')
->orderBy('created_at', 'ASC')
->lists('count', 'date');
您可以看到它使用查询范围方法ofType()
这是该方法,它只是在查询中添加了一堆额外的where子句:
return $query->where('list_name', '=', 'Apples')
->orWhere('list_name', '=', 'Oranges')
->orWhere('list_name', '=', 'Pears')
->orWhere('list_name', '=', 'Plums')
->orWhere('list_name', '=', 'Blueberries');
最终会产生以下真正的SQL查询:
SELECT DATE_FORMAT(DATE(`created_at`),'%b %d') as date,`created_at`, COUNT(*) as `count`
FROM `contacts`
WHERE `created_at` > '2014-10-02 00:00:00'
AND `list_name` = 'Apples'
OR `list_name` = 'Oranges'
OR `list_name` = 'Pears'
OR `list_name` = 'Plums'
OR `list_name` = 'Blueberries'
GROUP BY `date`
ORDER BY `created_at` ASC
问题是,WHERE created_at
> ' 2014-10-02 00:00:00'当OR条款启动时,将错过条款。由于运营商的优先权。我需要在括号中的第一个AND之后包装所有子句,如下所示:
SELECT DATE_FORMAT(DATE(`created_at`),'%b %d') as date,`created_at`, COUNT(*) as `count`
FROM `contacts`
WHERE `created_at` > '2014-10-02 00:00:00'
AND
(`list_name` = 'Apples'
OR `list_name` = 'Oranges'
OR `list_name` = 'Pears'
OR `list_name` = 'Plums'
OR `list_name` = 'Blueberries')
GROUP BY `date`
ORDER BY `created_at` ASC
所以,我的问题是,如何使用eloquent查询构建器实现此目的。谢谢。
答案 0 :(得分:4)
感谢mOrsa我已经弄清楚了,通过更改我的查询范围方法来利用高级位置:
return $query->where(function($query){
$query->orWhere('list_name', '=', 'Apples')
->orWhere('list_name', '=', 'Oranges')
->orWhere('list_name', '=', 'Pears')
->orWhere('list_name', '=', 'Plums')
->orWhere('list_name', '=', 'Blueberries');
});
我得到了所需的SQL。