【问题标题】:How to convert raw subquery into laravel query with query builder?如何使用查询生成器将原始子查询转换为 laravel 查询?
【发布时间】:2021-12-26 16:36:57
【问题描述】:

我编写了一个原始查询,其中还包含子查询。我不知道如何使用查询生成器转换 laravel 子查询中的子查询。 请有人转换此查询。这将是非常可观的。

查询:

SELECT inventory.EmployeeID,
        inventory.created_date AS OrderDate,
        SUM(inventory.calculation) AS TotalPrice
        FROM ( SELECT i.id AS ItemID,
        o.id AS OrderID,
        o.EmployeeID,
        o.created_date,
        (o.Quantity * i.price) AS calculation
        FROM `stationary_orders` AS o
        LEFT JOIN `stationary_items` AS i ON o.Stationary_ID = i.id
        WHERE o.Store IN $storess
        ORDER BY o.id DESC
        LIMIT $Limit,10 ) AS inventory
        GROUP BY inventory.EmployeeID

【问题讨论】:

标签: php sql laravel


【解决方案1】:

我花了一段时间才明白发生了什么。

据我从您的原始查询中了解到,这称为nested query

您可以使用 DB 外观来进行这样的查询:

  
  DB::select('inventory.EmployeeID, inventory.created_date AS OrderDate, SUM(inventory.calculation) AS TotalPrice')
    ->fromSub(function ($nestedQuery) use ($stores) {
      $nesterQuery->select('i.id ...')->from('stationary_orders as o')
        ->leftJoin('stationary_items', 'o.Stationary_ID', '=', 'stationary_items.id')
        ->whereIn('o.Store', $stores)
        ...
    }, 'inventory')
    ->groupBy('inventory.EmployeeID')->get()

【讨论】:

    猜你喜欢
    • 2023-01-14
    • 2015-12-13
    • 2019-11-03
    • 2021-12-11
    • 2023-03-07
    • 2019-10-14
    • 2019-03-09
    • 2021-08-07
    • 1970-01-01
    相关资源
    最近更新 更多