0

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

1
  • 1
    The way you currently word your question it might look like you expect other people to do you job. It would be better to reduce the SQL statement to the parts that give you trouble and indicate what you already tried to convert it. Commented Apr 9, 2020 at 11:07

1 Answer 1

1

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"));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.