Hello! I have the following SQL query I need to convert into Eloquent, but I'm having trouble wrapping my head around the Eloquent syntax.
SELECT
display.date, display.revenue, traffic.pageviews
FROM
(
SELECT date, SUM(revenue) AS revenue, sites_id
FROM
display
GROUP BY date , sites_id
) AS display
JOIN
(
SELECT date, SUM(pageviews) AS pageviews, sites_id
FROM
traffic
GROUP BY date , sites_id
) AS traffic
ON display.date = traffic.date
AND display.sites_id = traffic.sites_id
WHERE
display.date BETWEEN '2022-08-23' AND '2022-08-25'
You can see there are two sub-queries here; in the FROM and in the JOIN.
How would this be written in eloquent? Thank you in advance for any advice.
For a little more context (only if it helps), I am re-writing this query as it was taking 20+ seconds to execute if the user-provided date range was wide enough.
// App/Models/Display.php
$query = self::join('traffic', function($join)
{
$join->on(DB::raw("DATE_FORMAT(display.date, '%Y-%m-%d')"), '=', DB::raw("DATE_FORMAT(traffic.date, '%Y-%m-%d')"));
$join->on('display.sites_id', '=', 'traffic.sites_id');
})
->select(DB::raw($dateFormat . ' as granularity_date, sum(display.revenue) as revenue, sum(traffic.' . $metric . ') as ' . $metric . ''))
->whereBetween('display.date', $dateRange)
->groupBy('granularity_date')
->orderBy('granularity_date', 'asc');
// don't get hung up on the granularity_date thing, it is simply a user-provided value that groups the data by day/week/month/year.
Long story short, I converted it to SQL with ->toSql() and found that it was simple select / from / join:
// this is a simplified version of the real thing, just to demonstrate it's structure
SELECT DISTINCT
display.date, SUM(pageviews), SUM(revenue)
FROM
traffic
JOIN
display ON display.date = traffic.date
GROUP BY display.date
This query takes an extremely long time to execute. I rewrote it into the multi-subquery you see at the top of my question which reduced execution time from 20s+ to ~0.1s, and now my challenge is to convert it into a usable Eloquent function.
Again, thank you in advance!