你可以调整你们的关系来得到你想要的。接受的答案当然有效,但是对于大量数据来说可能会导致内存过度使用。
了解更多here http://softonsofa.com/tweaking-eloquent-relations-how-to-get-latest-related-model/ and there http://softonsofa.com/tweaking-eloquent-relations-how-to-get-n-related-models-per-parent/.
以下是如何使用 Eloquent 来实现此目的:
// Product model
public function latestPrice()
{
return $this->hasOne('Price')->latest();
}
// now we're fetching only single row, thus create single object, per product:
$products = Product::with('latestPrice')->get();
$products->first()->latestPrice; // Price model
这很好,但还有更多。想象一下您想要加载所有产品的最高价格(只是一个值):
public function highestPrice()
{
return $this->hasOne('Price')
->selectRaw('product_id, max(price) as aggregate')
->groupBy('product_id');
}
还不是很方便:
$products = Product::with('highestPrice')->get();
$products->first()->highestPrice; // Price model, but only with 2 properties
$products->first()->highestPrice->aggregate; // highest price we need
因此,添加此访问器可以使生活更轻松:
public function getHighestPriceAttribute()
{
if ( ! array_key_exists('highestPrice', $this->relations)) $this->load('highestPrice');
$related = $this->getRelation('highestPrice');
return ($related) ? $related->aggregate : null;
}
// now it's getting pretty simple
$products->first()->highestPrice; // highest price value we need