简体   繁体   中英

Sort and paginate a collection

I am having a lot of trouble sorting and then paginating a collection in laravel 4.

$articles = Article::get();
$articles->sortBy('category.name');

So I am getting all articles and then I am sorting them by name but when I try to do this:

$articles->paginate(30);

I get an error thrown. I tried all sorts of variations on the pagination, like paginate before sorting but that also doesn't work and all sorts of other things.

The relationship between articles and categories is like this:

class Article extends Eloquent {
    public function category(){
    return $this->belongsTo('Category');
    }
 }

class Category extends Eloquent {
  public function articles(){
     return $this->hasMany('Article');
  }
}

Am I missing the big picture here or where's my error?

You should use paginate right away, unless there is a very specific reason you want everything fetched and then manipulated.

$articles = Article::paginate(30);

or maybe

$articles = Article::where('category_id', '=', '5')->paginate(30);

or for sorting

$articles = Article::where('category_id', '=', '5')->sortBy('title')->paginate(30);

Your example makes me ask: what is sortBy('category.name') refering to? you are on the articles table, with no reference or whatever to the category table so this is (probably) wrong... is there a category_id field on your articles table for reference to the category? If you want to join the category table and sort articles by category name, you should try something like

 $articles = Category::where('id', 'IN', '5,6,7,8,9')->articles->paginate(30);

but this presumes you have kept the usual conventions, like having the category_id in articles, proper naming of the tables or otherwise declared the relation fields etc.

There are ways to manipulate a fetched collection, with closures. Copying from the documentation :

$roles = $roles->sortBy(function($role)
{
  return $role->created_at;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM