Christian Giupponi
Christian Giupponi

Reputation: 7618

Eloquent - Get related element

I have a table called images and for each image the users can vote it.
When the user vote the image I add a new row in my votes table to register the vote and the user_id.

Images:
- Id
- Image name

Votes:
- User_id
- Image_id

Now I need to get all the images ordered by the number of votes, how can I do?

I have added a new method in my Image.php file:

  public function votes()
    {
        return $this->hasMany( 'App\Vote' );
    }

Should I get all the images and then order it?

I was thinking about:

$images = Image::with('votes')->get();

Is it the correct way or there is a hidden function in eloquent to do so?

Upvotes: 2

Views: 81

Answers (1)

Pawel Bieszczad
Pawel Bieszczad

Reputation: 13325

Try this:

$images = Image::with('votes')->get()->sortByDesc(function($sort)
{
    return $sort->votes->count();
});

For pagination please check out the manual pagination

Upvotes: 2

Related Questions