这是我的基本查询:
$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未知列'p1.order_id' 在``where子句''中(SQL:SELECT MAX(p2.cancelled_at)FROM partner_orders p2,其中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"));
});
});
`
答案 0 :(得分:1)
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([...]);
})