我正在使用Laravel 4进行一个项目。
我有两张桌子,"拍卖"answers"出价",我想以最低的出价拍出所有的拍卖品。(我想得到所有的‘出价’模型)
我可以在SQlite中为每次拍卖编写查询,比如:
select *,min(bids.amount) from auctions,bids where auctions.id = bids.auction_id and auctions.id = 2 ;
我已经设置了关系拍卖hasMany("Bids")和Bids belongTo("auction"),这样我就可以打电话给
$auctions = Auction::with('bids')->get();
获取所有嵌套了Bids模型的拍卖,这样我就可以调用
$auctions->bids
在我看来,访问出价。
既然我不想获取100个出价并计算我的视图中的最低出价,那么将最低出价逻辑移动到模型中的最佳方法是什么?
更新
这两种解决方案都是有效的,实际上效果最好的是将其放入模型中
public function getLowestBidAttribute() {
return $this->bids()->orderBy('amount','asc')->first();
}
由于保持了应用程序的其余部分更干净,我可以定义其他方法来获得不同逻辑的出价。
您可以为此使用访问器:
// Auction model
public function getLowestBidAttribute()
{
return $this->bids()
->remember(1) // cache the query for a minute
->orderBy('amount', 'asc')->first();
}
// you can also check isset() lowestBid on $this->attributes, but this is a bit cleaner
// and most of the time caching query for a minute will be enough to avoid multiple queries
然后你可以很容易地访问它:
$auction->lowestBid; // Bid model you need
编辑:上面的代码对于单个拍卖来说是可以的,但当你获取拍卖集合时,它会导致n+1问题,我建议在代码中处理它,但这不是问题:
// Auction model
public function bids()
{
return $this->hasMany('Bid')->orderBy('amount','asc');
}
然后对集合使用first()方法:
// $auctions = Auction::with('bids')->get();
foreach($auctions as $auction)
{
$auction->bids->first(); // Bid model with lowest amount value
}
您可以迭代拍卖并获取每个拍卖的最小出价,如下所示:
foreach($auctions AS $auction) {
echo $auction->bids->min('bid');
}
在拍卖模型上,与deczo的答案相结合是更好的,也是你想要的:
function getMinBidAttribute() {
return $this->bids()->min('bid');
}
那么你可以这样称呼它:
foreach($auctions AS $auction) {
echo $auction->minBid;
}