0

I'm trying to convert my sql query to Laravel Query From this

SELECT products.name,
(SELECT SUM(orders.date BETWEEN from_date AND to_date)
FROM orders WHERE orders.product_id = products.id ) as order_counts
FROM products;

Then I tried converting to laravel query builder but it results to an error:

Product::select('name', 
DB::raw("SUM(orders.date 
BETWEEN $request->from_date AND $request->to_date) AS total_orders
FROM orders WHERE orders.product_id = products.id"))
->get();

The error is syntax error on the $request->from_date inside db::raw.

3
  • what's kind of error? Commented Oct 17, 2022 at 1:40
  • results in an error... provides no error description... Commented Oct 17, 2022 at 1:52
  • I edited the question and add the error message Commented Oct 17, 2022 at 5:30

1 Answer 1

1

You can use the withCount method: Documentation

Product::select('name')->withCount([
    'orders' => function (Builder $query) using ($from_date, $to_date) {
        $query->whereBetween('date', [$from_date, $to_date]);
     }
]);

I saw you have edited your issue, and describe your error. When using variables in string you should put them in braces.

Product::select('name', 
  DB::raw(
    "SUM(orders.date BETWEEN {$request->from_date} AND {$request->to_date}) AS total_orders FROM orders WHERE orders.product_id = products.id"
  )
)->get();
Sign up to request clarification or add additional context in comments.

2 Comments

How about I had these subquery: (SELECT SUM(orders.order_date BETWEEN '2022-10-06' AND '2022-10-12') - SUM(orders.order_date BETWEEN '2022-10-06' - INTERVAL 14 DAY AND '2022-10-12' - INTERVAL 7 DAY) FROM products WHERE orders.product_id = products.id) as diff_order,
You will have no other choice than using DB::raw method

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.