如何按照雄辩的laravel 5.1相关项目的数量来订购?

时间:2016-01-05 09:29:29

标签: php laravel eloquent laravel-5.1

我的拍卖有很多竞标者。现在我想订购每次拍卖的投标人数量的拍卖。我怎样才能做到这一点 ?

型号:Auction.php

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

我这样试过,但这显然是错的,但它给出了一个主意 我想要完成的事情。控制器:

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

2 个答案:

答案 0 :(得分:4)

尝试类似的东西......

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

答案 1 :(得分:0)

我也找到了这个答案:

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