在连接表上获得最新的价值与雄辩

编程入门 行业动态 更新时间:2024-10-28 12:17:54
本文介绍了在连接表上获得最新的价值与雄辩的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有两张这样的表:

产品:

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

了解更多 here 和 there 。

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

更多推荐

在连接表上获得最新的价值与雄辩

本文发布于:2023-10-30 08:19:01,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1542292.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:雄辩   表上   价值   最新

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!