首页 > 解决方案 > Laravel ORM + 原始查询表别名问题

问题描述

这是我的基本查询:

 $base_query = TableOne::join('table_two as p1', 'p1.order_id', '=', 'table_ones.id')
               ->join('table_threes as j1', 'p1.id', '=', 'j1.partner_order_id')
               ->select('table_ones.*')
               ->groupBy('table_ones.id', 'j1.status');

当有人需要过滤 table_two 表上的 partner_id 等数据时,我们添加一些额外的列,如下所示,

$base_query->where(function ($query) {
                   $query->whereNull('p1.cancelled_at');
                   $query->orWhere('p1.cancelled_at', '=', DB::select(DB::raw("SELECT MAX(p2.cancelled_at) FROM partner_orders p2 WHERE p2.order_id = p1.order_id")));
                   $query->whereNotExists(function ($query) {
                       DB::select(DB::raw("SELECT * FROM partner_orders p3 WHERE p3.order_id = p1.order_id AND p3.cancelled_at IS NULL"));
                   });
               });

但是在运行这个查询之后,他们是一个错误

SQLSTATE [42S22]:未找到列:1054 'where 子句'中的未知列'p1.order_id'(SQL:SELECT MAX(p2.cancelled_at) FROM partner_orders p2 WHERE p2.order_id = p1.order_id)

我认为,他们是该查询的一些问题。

$base_query->where(function ($query) {
    $query->whereNull('p1.cancelled_at');
    $query->orWhere('p1.cancelled_at', '=', DB::select(DB::raw("SELECT MAX(p2.cancelled_at) FROM partner_orders p2 WHERE p2.order_id = p1.order_id")));
    $query->whereNotExists(function ($query) {
        DB::select(DB::raw("SELECT * FROM partner_orders p3 WHERE
            p3.order_id = p1.order_id AND p3.cancelled_at IS NULL"));
        });
    });

`

标签: mysqllaravellaravel-5.2

解决方案


DB::select()直接执行查询。

在 的情况下orWhere(),仅使用原始表达式。

$query->orWhere('p1.cancelled_at', '=', DB::raw("(SELECT MAX(p2.cancelled_at) [...])"));

在 的情况下whereNotExists(),使用whereRaw()

$query->whereRaw("NOT EXISTS(SELECT * [...])");

在这两种情况下,您还可以使用闭包并手动构建查询:

$query->orWhere('p1.cancelled_at', '=', function($query) {
    $query->from('partner_orders')->select([...])->where([...]);
})

$query->whereNotExists(function($query) {
    $query->from('partner_orders as p3')->where([...]);
})

推荐阅读