Laravel分页不会重新初始化MySQL变量

时间:2018-11-10 12:07:40

标签: mysql laravel eloquent

如果我有此查询:

select 
    id,
    @product_rank := IF(@current_category = category_id, @product_rank + 1, 1) AS product_rank,
    @current_category := category_id
from products 

并使用Eloquent构建器创建查询:

Products::from(DB::raw('
    (select 
        id,
        @product_rank := IF(@current_category = category_id, @product_rank + 1, 1) AS product_rank,
        @current_category := category_id
    from products) as q 
'))->where('product_rank', '<=', 10)->paginate(5);

由于Laravel分页想要获取所有记录的总数,因此它执行一个额外的查询,如下所示:

select count(*) as aggregate from (
    select 
        id,
        @product_rank := IF(@current_category = category_id, @product_rank + 1, 1) AS product_rank,
        @current_category := category_id
    from products 
) q where product_rank <= 10

因此@current_category@product_rank不会重新初始化,并且主查询返回错误的结果。

我想知道是否有办法重新初始化两个变量。

0 个答案:

没有答案