Eloquent 处理mysql中的and & or 优先级
mysql中的and 和or 的优先级问题
MySQL中,AND的执行优先级高于OR。也就是说,在没有小括号()的干预下,总是先执行AND语句,再执行OR语句。
例如:
select * from table where 条件1 AND 条件2 OR 条件3
等价于
select * from table where ( 条件1 AND 条件2 ) OR 条件3
select * from table where 条件1 AND 条件2 OR 条件3 AND 条件4
等价于
select * from table where ( 条件1 AND 条件2 ) OR ( 条件3 AND 条件4 )
其实 and和or运算,就是逻辑运算中的 &(与) 和 |(或)运算。
eloquent中错误用法示例
假设我们需要过滤posts类型或者articles类型中上架状态的合集。简单的MySQL查询where条件如下所示:
... WHERE `status` = 1 and (type = "posts" or type = "articles")
接下来翻译成Eloquent方式查询:
// ...
$q->where('status', Collection::STATUS_ONLINE);
$q->where('type', 'articles');
$q->orWhere('type', 'posts');
但是上面这种方式翻译出来的sql语句可能并不是我们开头想象的那样:
... WHERE `status` = 1 and type = "posts" or type = "articles"
Eloquent并没有像想象的那样加上合适的括号
上面的语句实际执行的效果相当于:查询posts类型中上架状态的合集或者articles类型的合集
... WHERE (`status` = 1 and type = "posts") or type = "articles"
正确的写法为:
$q->where('status', Collection::STATUS_ONLINE);
$q->where(function ($query) {
$query->where('type', 'articles');
$query->orWhere('type', 'posts');
});
这种错误平时写的时候可能一不小心就犯了,关键是,这种失误不会抛出任何错误,很容逃过测试,需要写的时候就仔细注意。
这个人暂时没有 freestyle