dounieqi6959 2018-07-11 01:31
浏览 84

在select中求和多个ActiveQuery子查询

I have the following tables

Product

id name 
1  Alcohol
2  Candy
3  Soda

ProductIn

id item_no count date
1  1       10   2018/01/01
2  1       20   2018/01/07
3  2       10   2018/01/08
4  3       10   2018/01/08

ProductOut

id item_no count date 
1  1       10   2018/01/02 
2  1       10   2018/01/09 
3  2       2    2018/01/09
4  3       3    2018/01/11

I would like to get the sum of the product actual quantity by doing

select *, 
  (sum(select sum(count) from ProductIn where ProductIn.item_no = product.itemno) -
   sum(select sum(count) from ProductOut where ProductOut.item_no = product.itemno)) as availableQty
from product

currently im doing this like using ActiveQuery

$main_query = Product::find();

$data = [];
foreach ($main_query->all() as $model) {
    $query1 = ProductIn::find()
                ->filterWhere(['=', 'item_code', $model->item_no])
                ->asArray()->one();

    $query2 = ProductOut::find()
                ->filterWhere(['=', 'item_code', $model->item_no])
                ->asArray()->one();

    $allModels[$model->item_no] = ['item_no' => $model->item_no, 'name' => $model->name,  'availableQty' => ($query1 - $query2)];
}

but looping on every record is slow I wanted to combine the 3 ActiveQuery.

I was able to include the subquery to main_query by using

 $main_query->addSelect($query1)

but i cannot get the difference of the two subquery as one field.

Is there any way to do this on ActiveQuery?

  • 写回答

2条回答 默认 最新

  • dty5753 2018-07-11 04:40
    关注

    Here's few Suggestions for you -

    1. No need loop duplicate queries in forloop (i.e. $query1 & $query2)
    2. Just collect all item_codes required for ProductIn and ProductOut models from $main_query with the help of ArrayHelper::getColumn
    3. create 2 custom array's to store item_code with your query result(amount/quantity) in it & use this array in your foreach loop.

    You will find big time difference in execution.

    评论

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法