使用以下内容:
return $this->hasMany(Text::class, 'item_id')->where('item_type', 'product');
将进行如下查询:
select * from `texts` where `item_type` = 'product' and `texts`.`item_id` in ('1', '2', '3', '4', '5', '6', '7', '8', '9', '10')
我想要的是:
select * from `texts` where `texts`.`item_id` in ('1', '2', '3', '4', '5', '6', '7', '8', '9', '10') and `item_type` = 'product'
那么,在使用 hasMany() + 多个 where() 时如何更改 where 语句中的列顺序?
这是为了充分利用复合索引。
最佳答案
自 Illuminate\Database\Query\Builder有一个名为 wheres
的数组类型的公共(public)属性,您可以反转它。
$hasMany = $this->hasMany(Text::class, 'item_id')->where('item_type', 'product');
$eloquentBuilder = $hasMany->getQuery();
$queryBuilder = $eloquentBuilder->getQuery();
$queryBuilder->wheres = array_reverse($queryBuilder->wheres);
return $hasMany;
这会起作用,但我建议您至少尝试原始的 wheres。
参见:
Illuminate\Database\Query\Builder::whereRaw()
Illuminate\Database\Query\Builder::orWhereRaw()
希望对您有所帮助。
关于Laravel hasMany() + where() 以相反顺序返回 where 条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37823498/