alvaro_se
alvaro_se

Reputation: 345

Use an append attribute in a eloquent condition

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

Answers (1)

Jonas Staudenmeir
Jonas Staudenmeir

Reputation: 25906

You have two choices:

  • Get all travels and then filter them (not very efficient):
$travels = Travel::with('activities', 'expenses')->get()
    ->where('total_prize', '<=', $amount_available);
  • Recreate 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

Related Questions