Ric*_*haw 9 orm laravel eloquent
我有两个这样的表:
产品:
+----+-----------+
| id | name |
+----+-----------+
| 1 | Product 1 |
| 2 | Product 2 |
| 3 | Product 3 |
| 4 | Product 4 |
+----+-----------+
Run Code Online (Sandbox Code Playgroud)
价格:
+----+-------+------------+---------------------+
| id | price | product_id | created_at |
+----+-------+------------+---------------------+
| 1 | 20 | 1 | 2014-06-21 16:00:00 |
| 2 | 10 | 1 | 2014-06-21 17:00:00 |
| 3 | 50 | 2 | 2014-06-21 18:00:00 |
| 4 | 40 | 2 | 2014-06-21 19:00:00 |
+----+-------+------------+---------------------+
Run Code Online (Sandbox Code Playgroud)
我在产品上有这种关系:
public function prices()
{
return $this->hasMany('Price');
}
Run Code Online (Sandbox Code Playgroud)
我可以轻松地运行Product::with('prices')->get();以获得每个产品的每个价格.
我怎样才能使用Eloquent才能获得最新的价格?(另外,如果我想要最便宜/最昂贵的价格呢?)
Jar*_*zyk 24
你可以调整你的关系,以获得你想要的.接受的答案当然有效,但它可能是大量数据的内存过多.
以下是如何使用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
Run Code Online (Sandbox Code Playgroud)
这很好,但还有更多.想象一下,您想为所有产品加载最高价格(只是一个价值):
public function highestPrice()
{
return $this->hasOne('Price')
->selectRaw('product_id, max(price) as aggregate')
->groupBy('product_id');
}
Run Code Online (Sandbox Code Playgroud)
不太方便:
$products = Product::with('highestPrice')->get();
$products->first()->highestPrice; // Price model, but only with 2 properties
$products->first()->highestPrice->aggregate; // highest price we need
Run Code Online (Sandbox Code Playgroud)
因此,添加此访问器可以让生活更轻松:
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
Run Code Online (Sandbox Code Playgroud)