1

I'm working on a Laravel project where I need to calculate an estimated_value for each record in my SalesLead model by multiplying the probability and value columns. I want to filter records based on this computed column.

I used a global scope to add the computed column like this:

class EstimatedValueScope implements Scope
{
    public function apply(Builder $builder, Model $model): void
    {
        $builder->addSelect([
            '*',
            \DB::raw('COALESCE(probability, 0) * COALESCE(value, 0) * 0.01 AS estimated_value'),
        ]);
    }
}

And applied it to my model:

class SalesLead extends Model
{
    protected static function booted()
    {
        static::addGlobalScope(new EstimatedValueScope);
    }
}

I want to filter records using this computed column, for example:

$salesLeads = SalesLead::where('estimated_value', '>', 1000000)->get();

But I get an SQL error:

SQLSTATE[42703]: Undefined column: 7 ERROR:  column "estimated_value" does not exist
LINE 1: ...t count(*) as aggregate from "sales_leads" where ("estimated...
                                                         ^

Note: I need to use Eloquent's where method to filter by estimated_value, just like with any other column, and avoid using whereRaw or DB:Raw.

Questions:

  1. How can I properly filter and query based on this computed estimated_value column?
  2. Is using a global scope for this purpose the right approach? If not, what would be the best way to handle this?
  3. How can I ensure that the estimated_value column is included in the query and used correctly for filtering?

1 Answer 1

0

I believe that we have to use having instead of where for aggregated columns like estimated_value:

$salesLeads = SalesLead::having('estimated_value', '>', 1000000)->get();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.