简体   繁体   中英

paginate laravel 4 collection & sort by dynamically-generated variable

Fairly new to the Laravel framework / PHP frameworks in general and decided that I would build a Hacker News clone for my first project. However, I've run into a bit of a problem when I try to sort the results by the sorting algorithm and paginate the results.

Controller -

public function index()
{
    // tried Story::paginate(10) here instead, results in error
    $stories = Story::all();

    $stories = $stories->sortBy(function($story) 
    {
         return $story->getScore(); // returns score generated from HN algorithm
    })->reverse();

    return View::make('stories.index')->with('stories', $stories);
}

The view is just a "foreach($stories as $story)" loop.

The code above works fine, but is not paginated. Calling paginate before sortBy returns an error (Paginator class doesn't have the sortBy method) and calling paginate after sortBy also returns an error.

So how would I paginate the results AND sort by the dynamically-generated score? Thanks.

As the comments suggested, you can sort before it is paginated rather than after (which probably means using SQL to sort it, if you can, instead of sorting after the fact).

Anyway, I'm not sure exactly what fits your use case due to lack of information. Here's some ways you can use the Paginator object which might help you.

First, you can get the items from the Paginator object:

$stories = Story::paginate();
$models = $stories->getItems();
// And then sort them...

Second, if you need to sort the items and then re-paginate them , you can do that as well.

$stories = Story::all();
$stories->sortBy( ... );

$paginated = Paginator::make($stories, $total, $perpage);

None of my solutions will work exactly for you - for instance the last example here gets all, and then tries to sort them and paginate every story in the database (hardly what you want, defeats the purpose of pagination).

Hopefully this gives you some clue on how to use the pagination object if a way that might be useful.

Lastly, what I might suggest doing is making a background process (a command run on a cron job, for instance?) which ranks each article, and stores the ranked results in a cache. Then you can grab the story ID's in specific order from the cache and grab those from the database. Don't try to load every story in the database, sort them, and then return a subset of them on every page request made by a user.

Hope that helps.

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