本文介绍了在连接表上获得最新的价值与雄辩的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两张这样的表:

产品:

+----+-----------+
| id |   name    |
+----+-----------+
|  1 | Product 1 |
|  2 | Product 2 |
|  3 | Product 3 |
|  4 | Product 4 |
+----+-----------+

价格

+----+-------+------------+---------------------+
| 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 |
+----+-------+------------+---------------------+

我在产品上有这种关系:

I have this relationship on Product:

public function prices()
{
    return $this->hasMany('Price');
}

我可以轻松地运行 Product :: with价格) - > get(); 以获得每个产品的每个价格。

I can easily run Product::with('prices')->get(); to get each product with each of the prices it's had.

如何使用口才只得到最新的价格? (另外,如果我想要最便宜/最昂贵的价格呢?)

How can I use Eloquent to only get the most recent price? (Also, what if I wanted the cheapest/most expensive price instead?)

推荐答案

你可以调整你的关系,以获得你的想。接受当然的答案,但是它可能是大量数据的记忆过度。

You can tweak your relations to get what you want. Accepted answer of course works, however it might be memory overkill with lots of data.

了解更多和。

Find out more here and there.

以下是使用Eloquent的方法:

Here's how to use Eloquent for this:

// 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

这很好,但还有更多。想象一下,您想要为所有产品加载最高价格(只是一个值):

That's nice, but there's more. Imagine you'd like to load highest price (just a value) for all the products:

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

所以添加这个访问器让生活更轻松:

So add this accessor to make the life easier:

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

这篇关于在连接表上获得最新的价值与雄辩的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 03:39