Ad

How To Order By Count Of Related Items In Eloquent Laravel 5.1?

- 1 answer

I have Auctions who have many bidders. Now I want to order the auctions on the amount of bidders each auction has. How can I do this ?

model : Auction.php

public function bidders()
{
    return $this->hasMany('App\Bidder', 'FK_auction_id');
}

I tried it like this , but that is obviously wrong , but it gives an idea of what i'm trying to accomplish. Controller:

$auctions = Auction::orderBy($auction->bidders->count() , 'desc')->paginate(9);
Ad

Answer

Try something like that...

Auction::select('auctions.*, COUNT(bids.id) as bids_count')
->leftjoin('bids', 'bids.FK_auction_id', '=', 'auctions.id')
->groupBy('bids.id')->orderBy('bids_count', 'desc')->paginate(9);
Ad
source: stackoverflow.com
Ad