Jim Peeters
Jim Peeters

Reputation: 2863

how to order by count of related items in eloquent laravel 5.1?

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);

Upvotes: 1

Views: 2613

Answers (2)

Jim Peeters
Jim Peeters

Reputation: 2863

I have also found this answer :

$auctions = Auction::leftJoin('bidders','auctions.id','=','bidders.FK_auction_id')->
               selectRaw('auctions.*, count(bidders.FK_auction_id) AS `count`')->
               groupBy('auctions.id')->
               orderBy('count','DESC')->
               paginate(9);

Upvotes: 0

xAoc
xAoc

Reputation: 3588

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);

Upvotes: 4

Related Questions