php - Laravel Eloquent Pagination,如何在使用过滤器分页之前进行计数?

标签 php laravel eloquent laravel-query-builder

这里是我的代码:

$prestations = Prestation::with('service','facility','conciergeries.network')
            ->whereHas('service', function ($query) use ($searchService) {
                $query->select('id','name')->where('name', 'regexp', "/$searchService/i");
            })  
            ->whereHas('facility', function ($query) use ($searchPartenaire) {
                $query->select('id','name')->where('name', 'regexp', "/$searchPartenaire/i");
            })
            ->whereHas('conciergeries.network', function ($query) use ($searchFiliale) {
                $query->select('id','name')->where('name', 'regexp', "/$searchFiliale/i");
            })
                ->where('name', 'regexp', "/$search/i")
                ->orderBy($orderBy, $orderDirection)
                ->simplePaginate(50);

        $res = [
            'results' => $prestations,
            'total' => Prestation::all()->count(),
        ];

        return $res;

您好,实际上我得到的所有“Prestation”项目都是“总计”,但我需要在满足所有条件后 simplePaginate(50); 之前的真实总计。 我如何才能在不干扰我的代码的情况下将此值设置为“总计”? 谢谢!

最佳答案

Eloquent 查询非常灵活,您可以在执行它们之前将它们存储为变量。

这是您可以执行的操作的简化示例:

// Start your query and store it as a variable
$query = Prestation::where('name', 'regexp', "/$search/i");

// Now count the total number of entries which will return
$count = $query->count();

// Finally, do your pagination
$prestations = $query->simplePaginate(50);

当然,您可以将所有其他约束添加到查询中,我只是删除了它们以简化答案。

关于php - Laravel Eloquent Pagination,如何在使用过滤器分页之前进行计数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59580018/

相关文章:

php - 如何检测动画 GIF 的每秒滴答声?

php - Newbe,MySQL 查询跳过第一个条目 - 没有重复的 fetch_array

php - 使用 PHP 注册无效

php - 默认包含的 Blade 模板产量

php - Laravel 5.3 中的 concat 集合

php - 如何在 Laravel/Eloquent 中为多态表添加别名

php - 文件 routing.yml 不再工作

mysql - 如何在 Laravel 中表示有序递归关系?

php - 如何在 laravel 中日期相同的地方求和时间

Laravel如何通过绑定(bind)获取查询?