如何过滤Eloquent Laravel中的计算字段(追加)?

时间:2016-11-13 18:54:57

标签: php laravel-5 eloquent

我在模型室中计算了物业'价格'。

protected $appends = ['price'];

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

当我通过此虚拟字段过滤房间时......

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

当然我收到了错误 - 未找到列'价格'

如何用Laravel方式解决这个问题?

1 个答案:

答案 0 :(得分:0)

Eloquent有一个whereRaw方法,允许您手动构建查询的这一部分。

在您的情况下,您需要等效于SQL中的模型方法:

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

这会更复杂,具体取决于您的action列正在做什么,但这应该作为起点。