【问题标题】:How to convert a raw sql query in Laravel 6?如何在 Laravel 6 中转换原始 sql 查询?
【发布时间】:2021-01-16 03:19:12
【问题描述】:

我有一个在 Heidi SQL 中运行良好的查询。现在我需要在 Laravel 中编写相同的查询。但它并没有返回我在 Heidi SQL 中得到的确切结果。有人在这里帮我更新我的查询。提前致谢。

查询:

SELECT
    x.*,
    IFNULL(y.status_count, 0) 
FROM
    status x
LEFT JOIN (
    SELECT
        order_status,
        COUNT(id) AS status_count 
    FROM
        order_header
    WHERE
        user_id = 1
    GROUP BY
        order_status
) AS y
    ON x.code = y.order_status
WHERE
    x.type = 'ORD'

我在 Laravel 中写的:

$orderStatistics = OrderHeader::select(
        'status.id',
        'status.name',
        'status.description',
        'status.type',
        'status.code',                                                    
        DB::raw('order_status,count(*) as status_count'),
        DB::raw('IFNULL(`order_header`.`order_status`, 0)')
    )
    ->leftjoin('status', 'status.code', '=', 'order_header.order_status')
    ->orderBy('status.id')
    ->groupBy('order_status')
    ->where([
        ['order_header.user_id', $userID],
        ['status.type', 'ORD']
    ])
    ->get();

$userID 是单独分配的。我需要返回的是,如果在 order_header 表中没有为给定用户 ID 找到任何 order_status 以显示 order_status 计为 0。

目前,我获取给定用户 ID 的状态,我需要显示状态表中的所有状态,并且计数为 0。

【问题讨论】:

    标签: sql eloquent laravel-6 heidisql


    【解决方案1】:

    这是完全相同的查询。我自己没有测试过,但这是文档中显示的语法。

    $y = DB::table('order_header')
        ->select('order_status')
        ->selectRaw('COUNT(id) AS status_count')
        ->where('user_id', 1)
        ->groupBy('order_status');
    
    $query = DB::table('status', 'x')
        ->select('x.*')
        ->selectRaw('IFNULL(y.status_count, 0) AS status_count')
        ->leftJoinSub($y, 'y', function ($join) {
            $join->on('x.code', 'y.order_status');
        })
        ->where('x.type', 'ORD')
        ->get();
    

    【讨论】:

      猜你喜欢
      • 2018-10-11
      • 2019-02-03
      • 2021-09-11
      • 2023-01-14
      • 2013-09-27
      • 2019-05-31
      • 2017-01-05
      • 2020-02-07
      • 2021-08-19
      相关资源
      最近更新 更多