2017-06-05 185 views
1

我想prerform在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] 
+0

使用DBRaw()來定義計算列 –

+0

感謝@MarkBaker –

回答

2

您需要使用原始表達這樣的:

$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

+0

但他顯示此消息再次 –

+0

不能使用類型爲stdClass的對象作爲數組 –

+0

它的工作原理@Lorav感謝您 –