mysql - 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"));
});
});
`
解决方案
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([...]);
})
推荐阅读
- intellij-idea - Intellij idea 不在项目视图中显示文件夹
- xamarin - 如何在 Xamarin 表单中创建媒体下载器,例如 whats 应用程序、电报?以及如何创建whats app UI
- typescript - 打字稿:如何将通用字典类型传递给类,以便将空对象设置为默认值?
- scala - 如何针对可变和不可变 Map 进行编程?
- r - 计算数据框列中单元格之间的差异
- hbase - 从 hbase 1.2.5 中摆脱 Jetty 6
- excel - 数据透视表切片器未在未受保护的工作表中刷新
- node.js - Typescript 类型 HTTP 请求 Rest API
- video - 如何为 mp4 容器的视频流指定偏移量和查找位置?
- kdb - 如何让tickerplant编写日志文件?