laravelorm+raw查询表别名问题

7vux5j2d  于 2021-06-19  发布在  Mysql
关注(0)|答案(1)|浏览(409)

这是我的基本查询:

$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');

当有人需要筛选表2上的partner\u 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]:找不到列:“where子句”中的1054未知列“p1.order\u id”(sql:select max(p2.cancelled\u at)from partner\u orders p2 where p2.order\u id=p1.order\u 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"));
        });
    });

`

9cbw7uwe

9cbw7uwe1#

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([...]);
})

相关问题