How can I generate the equivalent of this (postgresql) query in eloquent
WITH result as (
select *, order_id as alias_id from orders
)
SELECT *
FROM result;
I should be able to pass the inner query as eloquent builder query.
How can I generate the equivalent of this (postgresql) query in eloquent
WITH result as (
select *, order_id as alias_id from orders
)
SELECT *
FROM result;
I should be able to pass the inner query as eloquent builder query.
2
Answers
As stated in the comment, Laravel does not support WITH clauses (common table expressions) in its query builder. You can however, pass it in raw.
I mentioned a package in the comment. One I’ve found that works well enough is
staudenmeir/laravel-cte
.Depending on your laravel version, you might need to install a specific version with
composer
.With that package installed, you can formulate your query like this so it looks the most as the original SQL:
You do not need the CTE (with expression). CTEs are an extension to sub-query concept. Initially so that that it could be reused instead of written for each use. But since you are using it just once a sub-query would be just fine. Your query can be rewritten as:
From your description I assume sub-query above is the inner query as eloquent builder query. Otherwise it reduces to
select *, order_id as alias_id from orders
.I do not know Laravel/Eloquent Query Builder but assume it should easily handle a simple sub-query.