Laravel - 在数据库表上查询最新日期的优雅方式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32153551/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel - Elegant way to query the latest date on a database table
提问by Chris Landeza
I have products and prices table (Temporal Data). what is the best approach for getting the latest price of a specific product? here's the basic structure of my two tables:
我有产品和价格表(时态数据)。获得特定产品最新价格的最佳方法是什么?这是我的两个表的基本结构:
products table:
-ID
-name
prices table
-ID
-product_id
-amount
-effective_datetime
Product Model:
产品型号:
public function prices()
{
return $this->hasMany('App\Price', 'product_id', 'id');
}
Price Model:
价格型号:
public function product()
{
return $this->belongsTo('App\Product', 'product_id');
}
Im currently using this code to get the latest price of a product:
我目前使用此代码来获取产品的最新价格:
$product->prices->sortByDesc('effective_datetime')->first()->amount
As you can imagine, I have to call that long line all over my application just to get the latest price of a product. is there a better way?
可以想象,我必须在整个应用程序中调用那条长线,才能获得产品的最新价格。有没有更好的办法?
My idea is to create a queryScope on my Price model like this:
我的想法是在我的价格模型上创建一个 queryScope,如下所示:
public function scopeLatest($query)
{
return $query->sortBy('effective_datetime', 'desc')->first();
}
and Call
并打电话
$product->prices->latest()->amount
but laravel is throwing an error "Call to undefined method Illuminate\Database\Eloquent\Collection::latest()"
但 Laravel 抛出错误“调用未定义的方法 Illuminate\Database\Eloquent\Collection::latest()”
采纳答案by Stuart Wagner
In order to apply scopes to a relationship, you have to call them on the relationship's method (rather than its dynamic property) to allow query chaining. Try this:
为了将范围应用于关系,您必须在关系的方法(而不是其动态属性)上调用它们以允许查询链接。尝试这个:
$product->prices()->latest()->amount
(Originally commented)
(原评论)
回答by user2094178
In your case it would be ideal to have an accessor:
在您的情况下,最好有一个访问器:
public function getPrice()
{
$this->prices()->sortBy('effective_datetime', 'desc')->first()->amount;
}
Now you can use it like $product->price
.
现在你可以像$product->price
.