Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

arithmetic operations in query builder laravel

i want to prerform this query in query builder of 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

so i write this

$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();

but he show an this error

[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]
like image 549
bondif Avatar asked Dec 18 '22 07:12

bondif


1 Answers

You need to use raw expression like that :

$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

like image 141
Lorav Avatar answered Jan 07 '23 17:01

Lorav