Retrieving/calculating Order total from OrderItems
I'm new to Laravel and trying to understand best practices as I build an eCommerce system.
Note, I'm on L5.1 atm, moving to 5.7, so solution must work on 5.1 right now.
I have an Order:
class Order extends Model
{
...
public function items()
{
return $this->hasMany('Statamic\Addons\Buck\Models\OrderItem');
}
}
and an OrderItem:
class OrderItem extends Model
{
...
public function order()
{
return $this->belongsTo('Statamic\Addons\Buck\Models\Order');
}
public function getTotalAttribute()
{
return $this->quantity * $this->price;
}
}
To get the Order total, I know I can use the collection sum method, but is that the "right" way to do it? Or is there an Eloquent way to do this that's better or more standard?
It's just about the performance. If you want to have the most performant solution, do it with the database query builder. Note,the Eloquent one wont work as you'd need to select a custom column that replaces the Accessor you have got - cause those are only available within the model, but not within the query builders.
In short, using the eloquent collection function sum() is totally fine, unless you are dealing with many entries that would take advantage of the database (I'd personally would say 10,000+ entries - may vary).
If you really need the performance though, you are better off using the query builder. It may even be easier for you to use a raw select as your query would have subselects.