过滤分页的 eloquent 集合 [英] filtering a paginated eloquent collection

查看:18
本文介绍了过滤分页的 eloquent 集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试过滤分页的 eloquent 集合,但是每当我使用任何集合方法时,我都会丢失分页.

I am trying to filter a paginated eloquent collection, but whenever I use any of the collection methods, I lose the pagination.

$models = User::orderBy('first_name','asc')->paginate(20);

$models = $models->each(function($model) use ($filters) {
    if(!is_null($filters['type'])) {
        if($model->type == $filters['type'])
            return $model;
    }

    if(!is_null($filters['state_id'])) {
        if($model->profile->state_id == $filters['state_id'])
            return $model;
    }

    if(!is_null($filters['city_id'])) {
        if($model->profile->city_id == $filters['city_id'])
            return $model;
    }
});

return $models;

我正在使用 Laravel 4.2,有没有办法保持分页?

I am working with Laravel 4.2, is there any way to persist the pagination?

推荐答案

根据您的具体情况扩展 mininoz 的回答:

Expanding on mininoz's answer with your specific case:

//Start with creating your object, which will be used to query the database

$queryUser = User::query();

//Add sorting

$queryUser->orderBy('first_name','asc');

//Add Conditions

if(!is_null($filters['type'])) {
    $queryUser->where('type','=',$filters['type']);
}

if(!is_null($filters['state_id'])) {
    $queryUser->whereHas('profile',function($q) use ($filters){
        return $q->where('state_id','=',$filters['state_id']);
    });
}

if(!is_null($filters['city_id'])) {
    $queryUser->whereHas('profile',function($q) use ($filters){
        return $q->where('city_id','=',$filters['city_id']);
    });
}

//Fetch list of results

$result = $queryUser->paginate(20);

通过对 SQL 查询应用适当的条件,您可以限制返回到 PHP 脚本的信息量,从而加快进程.

By applying the proper conditions to your SQL query, you are limiting the amount of information that comes back to your PHP script, and hence speeding up the process.

来源:http://laravel.com/docs/4.2/eloquent#querying-关系

这篇关于过滤分页的 eloquent 集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆