简体   繁体   中英

How to change SQL statement to laravel query

i have my sql query and i want to change into laravel Query

this is sql

SELECT 
products.id, 
 products.name, 
(select ifnull(sum(stocks.qty),0) from stocks where stocks.pid=products.id and DATE(stocks.created_at) 
= CURDATE()) as stock_in_today,

(select ifnull(sum(loadings.qty),0) from loadings where loadings.pid=products.id and 
  DATE(loadings.created_at) = CURDATE()) as total_loadings_today,

(select ifnull(sum(stocks.qty),0) from stocks where stocks.pid=products.id) as total_stock_till_date,

 (select ifnull(sum(loadings.qty),0) from loadings where loadings.pid=products.id) as 
total_loadings_till_date,

 ((select ifnull(sum(stocks.qty),0) from stocks where stocks.pid=products.id and 
 DATE(stocks.created_at) < CURDATE())-(select ifnull(sum(loadings.qty),0) from loadings where 
 loadings.pid=products.id and DATE(loadings.created_at) < CURDATE())) as opening_balance,

((select ifnull(sum(stocks.qty),0) from stocks where stocks.pid=products.id)-(select 
ifnull(sum(loadings.qty),0) from loadings where loadings.pid=products.id)) as closing_balance

  from products

someone can help on this

You can simply use the DB facade:

DB::select(DB::raw("SELECT 
products.id, 
 products.name, 
(select ifnull(sum(stocks.qty),0) from stocks where stocks.pid=products.id and DATE(stocks.created_at) 
= CURDATE()) as stock_in_today,

(select ifnull(sum(loadings.qty),0) from loadings where loadings.pid=products.id and 
  DATE(loadings.created_at) = CURDATE()) as total_loadings_today,

(select ifnull(sum(stocks.qty),0) from stocks where stocks.pid=products.id) as total_stock_till_date,

 (select ifnull(sum(loadings.qty),0) from loadings where loadings.pid=products.id) as 
total_loadings_till_date,

 ((select ifnull(sum(stocks.qty),0) from stocks where stocks.pid=products.id and 
 DATE(stocks.created_at) < CURDATE())-(select ifnull(sum(loadings.qty),0) from loadings where 
 loadings.pid=products.id and DATE(loadings.created_at) < CURDATE())) as opening_balance,

((select ifnull(sum(stocks.qty),0) from stocks where stocks.pid=products.id)-(select 
ifnull(sum(loadings.qty),0) from loadings where loadings.pid=products.id)) as closing_balance

  from products"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM