【发布时间】:2018-02-04 15:16:59
【问题描述】:
我有一个案例,我需要一个 联合查询,同时将最终结果作为 ActiveRecord。为了说明,我有两个表 Products 和 Categories。每个都有一个从 ActiveRecord 扩展的模型。我正在尝试如下查询
$deletedProducts = Products::find()->select([$productsTable . '.id', $productsTable . '.selling_price'])
->where(['client' => $clientId])
->andWhere(['<>', 'hidden', 0]);
和
$deletedCats = Category::find()->select([$catTable . '.id', $catTable . '.selling_price'])
->where(['client' => $clientId])
->andWhere(['<>', 'hidden', 0]);
和
$archivedItemsQuery = $deletedProducts->union($deletedCats);
然后我通过ActiveDataProvider
返回结果$dataProvider = new ActiveDataProvider(
[
'query' => $archivedItemsQuery,
]
]);
return $dataProvider->getModels();
问题是当我尝试在请求中发送分页数据,或者通过 ActiveDataProvider 设置时,没有发生分页。我当然可以将此查询更改为
$unionQuery = (new \yii\db\Query())
->from(['counter_items' => $archivedItemsQuery]);
这会导致正确的分页,但我没有得到 ActiveRecords 的结果。
关于如何使用 1 创建联合查询的任何想法。分页工作和 2. 结果是 ActiveRecord。
【问题讨论】:
-
如果你写
$dataProvider = new \yii\data\ActiveDataProvider([ 'query' =>Products::find()->from(['products' => $archivedItemsQuery]), 'pagination' => [ 'pageSize' => 8, ], ]);