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:
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()"
from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1h2Gm2X
via IFTTT
Aucun commentaire:
Enregistrer un commentaire