1

Hello I have in Product model variable appends with:

protected $appends = ['finalPrice'];

public function getFinalPriceAttribute()
{
    if ($this->discount_type == 1) {
        return intval($this->price -= $this->discount);
    } elseif ($this->discount_type == 0) {
        return intval($this->price * (1 - $this->discount / 100));
    }

    return $this->price;
}

When I want use this attribute on wherebetween I get error: undifined column finalPrice:

 $_products = Product::active()
        ->whereBetween('finalPrice', [$whereSum['min'], $whereSum['max']])
        ->orderBy($orderColumn, $orderBy);

How I can fix this?

Dumitru
  • 2,053
  • 6
  • 20
  • 45
  • Because this custom attribute is not part of the table, it is not selectable by a query. Eloquent queries translate to SQL queries. You could perform the filtering on a Collection, however for bigger datasets this might be slow. – online Thomas Dec 06 '18 at 10:12
  • @Thomas what I can do in this cause? – Dumitru Dec 06 '18 at 10:13

1 Answers1

0

Your Eloquent is:

$_products = Product::active()
        ->select('id',DB::raw("(CASE WHEN discount_type = 1 THEN price discount WHEN discount_type = 0 THEN price * (1 - / 100) END) as new_price)"))
        ->orderBy($orderColumn, $orderBy);
Dhruv Raval
  • 1,535
  • 1
  • 8
  • 15