Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

joshteam's avatar

Eloquent and RECUSRIVE / Complex Query

This MySQL works as expected, but I have no idea how to put this into Eloquent/Laravel.

WITH RECURSIVE dates as (
      SELECT
          curdate() as g_date,
          1 as days
      UNION ALL
      SELECT
          g_date - interval 1 day,
          days + 1
      FROM
          dates
      WHERE
          days < 30
     )
SELECT
    d.g_date as created_day,
    COALESCE(COUNT(b.id), 0) as total,
    d.days
FROM
    dates d
LEFT JOIN behaviors b
     ON b.child_id = 1 AND
        b.behavior_type_id  = 3 AND
        b.created_at >= d.g_date and
        b.created_at < d.g_date + INTERVAL 1 DAY
GROUP BY
    d.g_date;
0 likes
1 reply

Please or to participate in this conversation.