Laravel:WHERE子句中的数学

ste*_*esu 1 php mysql orm laravel eloquent

在SQL中,执行以下操作非常简单:

SELECT * FROM properties WHERE (price / acres) = 3000;
Run Code Online (Sandbox Code Playgroud)

这将选择"每英亩价格"为3000的每个房产

我希望在Laravel这样做.我尝试了以下方法:

Property::where('price / acres', 3000)->get();
Run Code Online (Sandbox Code Playgroud)

但是,这会在反引号中包含列标题,从而创建以下SQL:

select * from `properties` where `price / acres` = 3000
Run Code Online (Sandbox Code Playgroud)

这显然失败了(显然)错误: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'price / acres' in 'where clause'

Sau*_*ogi 6

你可以whereRaw像这样使用:

Property::whereRaw('(price / acres) = 3000')->get();
Run Code Online (Sandbox Code Playgroud)

  • 如果需要将数字作为变量传递,请将3000更改为?,然后传递它.`Property :: whereRaw('(price/acres)=?',[$ yourvariable]) - > get();`这不能用列名完成. (2认同)