Chr*_*len 6 mysql operator-precedence operator-keyword laravel eloquent
我使用 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');
Run Code Online (Sandbox Code Playgroud)
你可以看到它使用了一个查询范围方法ofType()
这是那个方法,它只是向查询添加了一堆额外的 where 子句:
return $query->where('list_name', '=', 'Apples')
->orWhere('list_name', '=', 'Oranges')
->orWhere('list_name', '=', 'Pears')
->orWhere('list_name', '=', 'Plums')
->orWhere('list_name', '=', 'Blueberries');
Run Code Online (Sandbox Code Playgroud)
最终这会产生以下真实的 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
Run Code Online (Sandbox Code Playgroud)
问题是,created_at
当 OR 子句开始时, WHERE > '2014-10-02 00:00:00' 子句被遗漏了。由于运算符优先级。我需要将第一个 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
Run Code Online (Sandbox Code Playgroud)
所以,我的问题是,我将如何使用 eloquent 查询构建器来实现这一点。谢谢你。
感谢 mOrsa,我想通了,通过更改我的查询范围方法来利用高级 where:
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');
});
Run Code Online (Sandbox Code Playgroud)
我得到了想要的 SQL。