Yii2 QueryBuilder 和 Filter 与子查询结果比较

问题描述 投票:0回答:1

我在Yii2中有一个查询如下:

$Query = (new Query())
->select([
    'i.id as order_id',
    'i.uid as order_uid',
    'i.status as order_status',
    'i.created as order_created',
    'i.car_id as car_id',
    'i.user_id as user_id',
    'cc.customer_id as customer_id',
    'cc.make_id as make_id',
    'cc.model_id as model_id',
    'cc.color_id as color_id',
    'cc.plate_country as plate_country',
    'cc.plate_text as plate_text',
    'mk.title as make_title',
    'md.title as model_title',
    'c.title as customer_title',
    '(select coalesce(sum(cost),0) from moneyflow where order_uid = i.uid and type_id = 14) as total_paid',
    '(select (select coalesce(sum(cost),0) from workflow where order_uid = i.uid) + (select coalesce(sum(cost),0) from partsflow where order_uid = i.uid) + (select coalesce(sum(cost),0) from moneyflow where flow = -1 and type_id != 13 and order_uid = i.uid)) as order_total'
])
->from('orders i')
->leftJoin('customer_cars cc','i.car_id = cc.id')
->leftJoin('car_makes mk','cc.make_id = mk.id')
->leftJoin('car_models md','cc.model_id = md.id')
->leftJoin('customers c','cc.customer_id = c.id')
->where(['i.status' => 2])
->andFilterCompare('(select coalesce(sum(cost),0) from moneyflow where order_uid = i.uid and type_id = 14)','< order_total')
->all();

因此,我想查看状态= 2且total_paid小于order_total的所有订单 问题是当我将“order_total”添加到“addFilterCompare”时,我没有得到任何结果。 有线索吗?

php sql yii2
1个回答
0
投票

最终得到了这个解决方案

$total_paid = (new Query())->select(['coalesce(sum(cost),0)'])->from('moneyflow')->where('order_uid = i.uid')->andWhere(['=','type_id',14]);
$total_expenses = (new Query())->select(['(select (select coalesce(sum(cost),0) from workflow where order_uid = i.uid) + (select coalesce(sum(cost),0) from partsflow where order_uid = i.uid) + (select coalesce(sum(cost),0) from moneyflow where flow = -1 and type_id != 13 and order_uid = i.uid)) as total_expenses']);
$Query = (new Query())
->select([
    'i.id as order_id',
    'i.uid as order_uid',
    'i.status as order_status',
    'i.created as order_created',
    'i.car_id as car_id',
    'i.user_id as user_id',
    'cc.customer_id as customer_id',
    'cc.make_id as make_id',
    'cc.model_id as model_id',
    'cc.color_id as color_id',
    'cc.plate_country as plate_country',
    'cc.plate_text as plate_text',
    'mk.title as make_title',
    'md.title as model_title',
    'c.title as customer_title',
    'total_paid' => $total_paid,
    'total_expenses' => $total_expenses,
])
->from('orders i')
->leftJoin('customer_cars cc','i.car_id = cc.id')
->leftJoin('car_makes mk','cc.make_id = mk.id')
->leftJoin('car_models md','cc.model_id = md.id')
->leftJoin('customers c','cc.customer_id = c.id')
->where(['i.status' => 2])
->andFilterCompare($total_paid,$total_expenses,'<');
© www.soinside.com 2019 - 2024. All rights reserved.