Reputation: 345
this is my situation of my laravel project:
So far so good. My problem is when I try to apply the filter 'available_amount <= total_prize' to Travel's list.
How can I use the append attribute 'total_prize' for get all travels less than the amount_available?
This is the accessor for total_prize attribute:
public function getTotalPrizeAttribute()
{
return (float) $this->activities->sum('prize') + $this->expenses->sum('prize');
}
I want to do something like this:
Travel::where('total_prize', '<=', 'amount_available')->get();
Upvotes: 1
Views: 4513
Reputation: 25906
You have two choices:
$travels = Travel::with('activities', 'expenses')->get()
->where('total_prize', '<=', $amount_available);
getTotalPrizeAttribute()
in the query:$travels = Travel::withCount([
'activities' => function($query) {
$query->select(DB::raw('sum(prize)'));
},
'expenses' => function($query) {
$query->select(DB::raw('sum(prize)'));
}
])
->having(DB::raw('activities_count + expenses_count'), '<=', $amount_available)
->get();
Upvotes: 3