【问题标题】:How to convert left join lateral SQL query to Laravel Eloquent query?如何将左连接横向 SQL 查询转换为 Laravel Eloquent 查询?
【发布时间】:2021-08-10 10:38:48
【问题描述】:

我想在 Eloquent 查询中转换以下 Postgre SQL 查询:

SELECT ncts_info.nct_id, A.agency_model, ncts_info.indexation_id
FROM ncts_info
LEFT JOIN (
    drug_centers LEFT JOIN LATERAL json_to_recordset(nct_numbers) AS tbl(nct_number text) ON true
) A ON A.nct_number = ncts_info.nct_id

如何将其转换为 Eloquent 查询?

【问题讨论】:

    标签: php sql laravel postgresql eloquent


    【解决方案1】:

    我设法以某种方式部分获得了正确的 Laravel 查询,但缺少一些东西:

    NctsInfo::leftJoin('drug_centers', function($join) {
       $join->leftJoin(DB::raw('LATERAL json_to_recordset(nct_numbers) AS tbl(nct_number text)'), DB::raw('1'), '=', DB::raw('1'));
       $join->on(DB::raw('dc.nct_number'), '=' ,DB::raw('ncts_info.nct_id'));
    })
    ->whereNotNull("nct_numbers")->get();
    

    但根据我预期的 sql 查询:

    SELECT ncts_info.nct_id, A.agency_model, ncts_info.indexation_id FROM ncts_info
    LEFT JOIN (
        drug_centers LEFT JOIN LATERAL json_to_recordset(nct_numbers) AS tbl(nct_number text) ON true
    ) A ON A.nct_number = ncts_info.nct_id
    

    我需要将我的第一个左连接“别名”为“A”以获取我的 nct_number 字段。

    有人知道怎么解决吗?

    感谢您的帮助

    【讨论】:

      【解决方案2】:

      我发现最好的方法是先定义一个子查询。来自 laravel 文档:

      Posts = DB::table('posts')
      ->select('user_id', DB::raw('MAX(created_at) as last_post_created_at'))
                     ->where('is_published', true)
                     ->groupBy('user_id');
      
      $users = DB::table('users')
          ->joinLeftSub($latestPosts, 'latest_posts', function ($join) {
              $join->on('users.id', '=', 'latest_posts.user_id');
          })->get();
      

      【讨论】:

        【解决方案3】:

        你可以像在 laravel 中那样使用 DB

        $data = DB::table('ncts_info')
        ->leftJoin('drug_centers', 'drug_centers.foreign_key', 'ncts_info.id')
        ->select('ncts_info.nct_id','A.agency_model','ncts_info.indexation_id')
        ->get();
        

        这将产生以下查询:

        SELECT "ncts_info"."nct_id", "A"."agency_model", "ncts_info"."indexation_id"
        FROM "ncts_info"
        LEFT JOIN "drug_centers" ON "drug_centers"."foreign_key" = "ncts_info"."id";
        

        【讨论】:

        • 这没有回答问题。它不会产生 OP 想要的相同查询。
        • 不幸的是,这对我没有帮助。我需要包含 LATERAL 子句:/
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-10-03
        • 1970-01-01
        • 1970-01-01
        • 2019-02-05
        • 2015-02-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多