【问题标题】:Laravel pagination breaks if fetching total count of data after getting the result set. Any idea why?如果在获取结果集后获取数据总数,Laravel 分页会中断。知道为什么吗?
【发布时间】:2020-06-12 16:25:33
【问题描述】:
public function index(Request $request)
    {

        $params = $request->except('_token');

        $profiles = Profile::filter($params);

        $resultsSet = [
            "result_count" => $profiles->count(),
            "data" => $profiles->skip( ($params['page_number'] - 1) * $params['page_size'] )->take($params['page_size'])->get()
        ];

        return json_encode($resultsSet);
    }

这是有效的。但是,一旦我切换 $resultSets 的顺序,当 page_number 大于 1 时,生成的 count() 值就会开始给我 0。$resultsSet 的切换代码是:

$resultsSet = [
            "data" => $profiles->skip( ($params['page_number'] - 1) * $params['page_size'] )->take($params['page_size'])->get(),
            "result_count" => $profiles->count()
        ];

为什么会这样?谢谢。

【问题讨论】:

    标签: laravel laravel-pagination


    【解决方案1】:

    这是因为$profiles 数据在对其进行skip 操作之后被操纵,
    您可以做的是克隆变量并像这样使用它以使您的计数不受影响。

        $profiles = Profile::filter($params);
        $temp = clone $profiles  // This is will make exact copy of your $profile variable
    
        $resultsSet = [
            "result_count" => $temp->count(),
            "data" => $profiles->skip( ($params['page_number'] - 1) * $params['page_size'] )->take($params['page_size'])->get()
        ];
    

    现在,即使您颠倒顺序,计数也不会受到影响

    $resultsSet = [
                "data" => $profiles->skip( ($params['page_number'] - 1) * $params['page_size'] )->take($params['page_size'])->get(),
                "result_count" => $temp->count(),
            ];
    

    我希望我解释得很好。

    【讨论】:

    • 谢谢。你的回答确实让我更进一步,但它仍然不能解释为什么现在计数为 0。
    • 我告诉过你,如果 $profiles 放在前面,它会被操纵,如果它放在 @SaketJain 之后会影响 $profiles 的计数
    • 是的,我明白了。但是为什么是0呢?我的意思是它应该只是通过我跳过的配置文件数量来减少(这就是我期望的通常行为)
    • @SaketJain 你必须验证你的查询,看看它是否在做一些意想不到的事情
    猜你喜欢
    • 2012-04-07
    • 1970-01-01
    • 2015-04-12
    • 1970-01-01
    • 2020-06-25
    • 2019-12-16
    • 1970-01-01
    • 1970-01-01
    • 2019-09-09
    相关资源
    最近更新 更多