您好,我需要帮助,如何使用Laravel的查询构建器进行此选择?我知道我可以使用原始的SQL查询,但我想避免这种情况。任何帮助将不胜感激,提前谢谢!
SELECT SUM(COST) FROM (
SELECT COUNT(STOCK_ID)*PRICE COST
FROM STOCK ST INNER JOIN PRODUCT PDT ON PDT.PROD_ID=ST.PROD_ID
WHERE PROD_NAME='PENCIL' LIMIT 6 GROUP BY STOCK_ID) TB
我之所以避免使用原始sql是因为当我尝试这样的时候
private function totalprice( $product_id)
{
$selltotal =
DB::raw("SELECT SUM(sell_rate)
FROM
(SELECT COUNT(stock_id) * stock_rate
FROM tbl_stock AS st
INNER JOIN tbl_product AS pdt ON pdt.product_id = st.produck_id
WHERE produck_name = 'product_id'
LIMIT 6)
GROUP BY stock_id");
return $selltotal;
}
这是我得到的错误
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT SUM(sell_rate)
FROM
(SELECT COUNT(stock_id) * stock_rate ' at line 1 (SQL: insert into `tbl_sell` (`category_id`, `brand_id`, `product_id`, `buyer_id`, `sell_quantity`, `sell_total_price`, `sell_date`, `added_by`, `entry_time`) values (3, 5, 6, 3, 2, SELECT SUM(sell_rate)
FROM
(SELECT COUNT(stock_id) * stock_rate
FROM tbl_stock AS st
INNER JOIN tbl_product AS pdt ON pdt.product_id = st.produck_id
WHERE produck_name = 'product_id'
LIMIT 6)
GROUP BY stock_id, 2017-08-11, 0, 2017-08-11 07:34:11))
如果我能解决问题,请非常高兴。提前致谢
答案 0 :(得分:1)
你好,我自己成功了。有一天它可能对某人有所帮助
private function totalprice( $product_id)
{
$selltotal = DB::table('tbl_stock')
->select(array(DB::raw('count(stock_id)*stock_rate')))
->where('tbl_stock.product_id', $product_id)
->join('tbl_product','tbl_stock.product_id','=', 'tbl_product.product_id')
->groupby('stock_id')
->sum('stock_rate');
return $selltotal;
}