【问题标题】:arithmetic operations in query builder laravel查询生成器 laravel 中的算术运算
【发布时间】:2017-11-06 03:54:44
【问题描述】:

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

【问题讨论】:

  • 使用 DBRaw() 定义计算列

标签: php mysql sql laravel laravel-5


【解决方案1】:

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

$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

【讨论】:

  • 不能使用 stdClass 类型的对象作为数组
  • 作为提示,您也可以使用selectRawselectRaw('products.*, (products.price * discounts.tauxDiscount/100) as newPrice')
猜你喜欢
  • 2018-05-07
  • 1970-01-01
  • 2016-08-30
  • 2017-08-21
  • 1970-01-01
  • 1970-01-01
  • 2021-06-23
  • 2016-04-23
  • 1970-01-01
相关资源
最近更新 更多