2

I have something like this

class Item extends Model
{   
    ...
    public function likes() {
    return $this->hasMany('like');
}
...

In my controller I load this item like this

$items = Item::with([
        ...
        'likes',
        'comments',
        ...
    ])
        ->paginate(10);

I need to get likes count and order this list with paginate by this number something like this

$items = Item::with([
        ...
        'likes',
        'comments',
        ...
    ])
        ->orderBy(likes->count())
        ->paginate(10);

, which obviously is not working. Any tips ? Thanks.

SaKer
  • 107
  • 2
  • 11

2 Answers2

5

Just a solution. But I think there has a better one

$items = Item::with([
        ...
        'likes',
        'comments',
        ...
    ])
        ->withCount('likes')
        ->orderBy('likes_count','DESC')
        ->paginate(10);
KmasterYC
  • 2,294
  • 11
  • 19
0

Try this an see if you get your desired output

$items = Item::with([
    ...
 'likes'=>function($query){
 $query->selectRaw('likes.*,count(likes.LikeID) as LikesCount')->groupBy('Item.itemID');
 },
    'comments',
    ...
])
    ->orderBy('likes.Likescount','DESC')
    ->paginate(10);
Hamza Dairywala
  • 482
  • 2
  • 11