查询生成器laravel中的算术运算

时间:2017-06-05 11:23:56

标签: php mysql sql laravel laravel-5

我想在laravel 5.4

的查询构建器中预先执行此查询
select title, price,  price*tauxDiscount/100 as newPrice
from products p, hasdiscount pd, discounts d
WHERE p.idProd = pd.idProd
and d.idDiscount = pd.idDiscount
and now() BETWEEN dateStart and dateEnd

所以我写这个

$products =  DB::table('products')
        ->join('hasDiscount', 'products.idProd', '=', 'hasDiscount.idProd')
        ->join('discounts', 'discounts.idDiscount', '=', 'hasDiscount.idDiscount')
        ->select('products.*', '(products.price * discounts.tauxDiscount / 100) as newPrice')
        ->get();

但是他显示了这个错误

[SQLSTATE[42S22]: Column not found: 1054 Unknown column '(products.price 
* discounts.tauxDiscount / 100)' in 'field list' (SQL: select 
`products`.*, `(products`.`price * discounts`.`tauxDiscount / 100)` as 
`newPrice` from `products` inner join `hasDiscount` on 
`products`.`idProd` = `hasDiscount`.`idProd` inner join `discounts` on 
`discounts`.`idDiscount` = `hasDiscount`.`idDiscount`)][1]

1 个答案:

答案 0 :(得分:6)

你需要使用这样的原始表达式:

$products =  DB::table('products')
        ->join('hasDiscount', 'products.idProd', '=', 'hasDiscount.idProd')
        ->join('discounts', 'discounts.idDiscount', '=', 'hasDiscount.idDiscount')
        ->select(DB::raw('products.*,(products.price * discounts.tauxDiscount/100) as newPrice'))
        ->get();

https://laravel.com/docs/5.4/queries#raw-expressions