Jun 17, 2020
0
Level 19
From subquery syntax
Hi,
Since laravel 6 there is the ability to add From Subquery statements.
https://github.com/laravel/framework/pull/29602
The examples given for the syntax are this:
$query->select('name')
->from(function ($query) {
$query->something();
}, 'users')
->get();
DB::table(function ($query) {
$query->something();
}, 'users')->get();
I'm very confused whats the difference between the two and how to implement it. Given I have the following postgres query to find consecutive date streaks when a given user does a session.
SELECT COUNT(*) streak, SUM(amount) streakAmount, MIN(date) startDate, MAX(date) endDate,
dateMinusRow dateMinusRow
FROM (
SELECT
COUNT(*) amount,
date_trunc('day', start) date,
date_trunc('day', start) - INTERVAL '1' DAY * DENSE_RANK() OVER (ORDER BY date_trunc('day', start)) dateMinusRow
FROM sessions
WHERE user_id = ".$this->user->id."
GROUP BY date_trunc('day', start)
) groupedDays
GROUP BY dateMinusRow
I'm having trouble understanding how to add the surrounding query, I think I got the from() part down:
DB::table(function ($query) {
$query->selectRaw("
COUNT(*) amount,
date_trunc('day', start) date,
date_trunc('day', start) - INTERVAL '1' DAY * DENSE_RANK() OVER (ORDER BY date_trunc('day', start)) dateMinusRow"
)->from('sessions')
->where('user_id', $this->user->id)
->groupByRaw("date_trunc('day', start)");
}, 'groupedDays')
But I don't understand how I should put the top level select and groupBy clauses
Please or to participate in this conversation.