【问题标题】:Postgres function WITH in Laravel QueryBuilderLaravel QueryBuilder 中的 Postgres 函数 WITH
【发布时间】:2017-03-28 20:40:44
【问题描述】:

请帮帮我。

我有原始 SQL

WITH collections AS (
    SELECT 
        ...
    FROM
        ...
)
SELECT
    ...
FROM collections c1
LEFT JOIN collections c2
    ...

如何使用 Laravel QueryBuilder 编写它?

【问题讨论】:

  • Laravel QueryBuilder 不支持WITH 语法。您有 2 个选项:重写不带“WITH”的查询或使用接受原始 sql 查询的 DB::select()。

标签: postgresql laravel laravel-query-builder


【解决方案1】:

您可以使用 Laravel 查询构建器 (https://laravel.com/docs/5.3/queries#raw-expressions) 的 RAW 方法。请小心潜在的 SQL 注入漏洞。

【讨论】:

  • 现在我正在这样做:$queryResult = DB::select(" with collections AS (SELECT .....))";
  • 您可以发布您所做的整个查询语句吗?
  • $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,...]);
  • 您查看过我提供的网址吗?您必须使用 DB::raw 而不是 DB::select。
  • @IlyaPoluhin,您可以像这样使用 DB::raw DB::raw('SELECT * FROM table...)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-09-16
  • 2015-06-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-18
相关资源
最近更新 更多