【发布时间】:2018-07-11 01:31:55
【问题描述】:
我有以下表格
产品
id name
1 Alcohol
2 Candy
3 Soda
产品输入
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
产品输出
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
我想得到产品实际数量的总和 通过做
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
目前我正在这样做,就像使用 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)];
}
但是在每条记录上循环很慢我想结合 3 个 ActiveQuery。
我能够通过使用将子查询包含到 main_query 中
$main_query->addSelect($query1)
但我无法将两个子查询的区别作为一个字段。
有没有办法在 ActiveQuery 上做到这一点?
【问题讨论】:
-
也添加预期的查询结果。
标签: php activerecord yii2