please help me.
I've got the raw SQL
WITH collections AS (
SELECT
...
FROM
...
)
SELECT
...
FROM collections c1
LEFT JOIN collections c2
...
How I can write it using Laravel QueryBuilder?
You may use the RAW method of Laravel's Query Builder (https://laravel.com/docs/5.3/queries#raw-expressions). Just be careful with potential SQL injection loopholes.
$queryResult = DB::select(" with collections AS ( SELECT tcm.shop_id, ... FROM template_collection_menu AS tcm LEFT JOIN template_collection AS tc ON tc.id = tcm.template_collection_id WHERE tcm.shop_id IN (:mainShopId, :currentShopId) ORDER BY tcm.position ASC ) SELECT COALESCE(c2.shop_id, c1.shop_id) as shop_id, ... FROM collections c1 LEFT JOIN collections c2 ON c2.template_collection_id = c1.template_collection_id AND c1.shop_id = :mainShopId AND c2.shop_id = :currentShopId WHERE c1.shop_id = :mainShopId ", ['mainShopId' => $mainShopId,...]);
WITHsyntax. You have 2 options: rewrite query without 'WITH' or use DB::select() which accepts raw sql queries.