foozoor
foozoor

Reputation: 503

Count relation and orderBy with Laravel 4?

This is my index action from my TagsController:

if(Input::get('filter') == 'most-used')
{
    $tags = Tag::with('questions')->orderBy('name', 'asc')->paginate(10);
    return View::make('tags.index', compact('tags'));
}

I would like the tags with the most questions first.

How do you do that?

Thanks in advance!

Upvotes: 0

Views: 336

Answers (2)

Samuel De Backer
Samuel De Backer

Reputation: 3461

Here is how I did it :

if(Input::get('filter') == 'most-used')
{
    $tags = Tag::select(
            '*',
            DB::raw("(SELECT COUNT(*) FROM `questions_tags` WHERE `tag_id` = `tags`.`id`) AS 'count'")
        )
        ->orderBy('count', 'desc')
        ->paginate(10);
    return View::make('tags.index', compact('tags'));
}

Upvotes: 1

Ayobami Opeyemi
Ayobami Opeyemi

Reputation: 752

Try this:(untested)

$tags = Tag::with('questions')->orderBy('name', 'asc')->paginate(10);
$tags = $tags->sortBy(function($tag){
    return $tag->questions->count();
});
return View::make('tags.index', compact('tags'));

Upvotes: 0

Related Questions