Laravel hasMany() + where() 以相反顺序返回 where 条件

标签 laravel laravel-5

使用以下内容:

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/

相关文章:

php - Laravel 命令总线,何时使用自处理命令?

php - Laravel @foreach 在 Blade 中导致错误

php - 有没有办法在 Laravel Dusk 中断言当前 URL 值?

php - Laravel 5.2 - PHPExcel_Writer_Exception : Unable to load PDF Rendering library in

php - Laravel multiauth md5 和主键字符串

javascript - 如何使用 then() 将 Fetch 响应的 JSON 主体传递给 Throw Error()?

php - Laravel 验证 : bail rule not working

laravel - 在 Laravel 中找不到类 'Illuminate\Foundation\Application'

laravel - Laravel Eloquent 中关系内部的查询关系

php - 如何使用 DB::raw 查询输出 MySQL 版本