Laravel 如果在获取结果集后获取数据总数,分页会中断。知道为什么吗?
Laravel pagination breaks if fetching total count of data after getting the result set. Any idea why?
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()
];
为什么会这样?谢谢。
这是因为 $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(),
];
希望我解释的很好
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()
];
为什么会这样?谢谢。
这是因为 $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(),
];
希望我解释的很好