I have written this SQL and now I need to convert it to Laravel Query Builder.
The idea is that I can get the age of a date field. I did it by using the PostgreSQL built in method called age, the thing is that I need to filter users by the age, for example, users with age equal or greater than 24.
There are two ways to accomplish this:
The table:
CREATE TABLE test (
id INT,
name VARCHAR(255),
birthdate DATE
);
INSERT INTO test (id, name, birthdate) VALUES (1, 'jhon', '1975-12-12');
INSERT INTO test (id, name, birthdate) VALUES (2, 'doe', '1994-12-12');
The queries:
- CTE approach (Common Table Expressions)
WITH cte as (
SELECT *, extract(year from age(birthdate)) as age
FROM test
)
SELECT id, name, birthdate
FROM cte
WHERE age >= 24
- Lateral join approach
select *
from test cross join lateral
(values (extract(year from age(birthdate)))
) v(age)
where v.age >= 24;
If you want to see it live: https://www.db-fiddle.com/f/qA8znjMzm4NR9wdCo5pssX/2
How can I convert one of the approaches (or both) to use Laravel Query Builder?
Thank you very much.