简体   繁体   中英

How filter on calculated field (append) in Eloquent Laravel?

I have calculated property 'price' in model Room.

protected $appends = ['price'];

public function getPriceAttribute()
{
    if ($this->action) return $this->action_price_per_meter*$this->area;
    return $this->price_per_meter*$this->area;
}

When i filter Rooms by this virtual field ...

$rooms = Room::where('price','<',100000)->get();

of course i got error - Column 'price' not found

How to solve this problem in Laravel way?

Eloquent has a whereRaw method which allows you to construct that segment of the query manually.

In your case you need the equivalent of the model's method in SQL:

->whereRaw('price_per_meter * area < 100000')

It'll be more complicated depending on what your action column is doing but that should serve as a starting point.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM