Yii2 - 将分页联合查询到 ActiveRecord

Yii2 - Union query with Pagination into ActiveRecord

我有一个案例需要联合查询,同时最终结果是ActiveRecord。为了说明,我有两个表 ProductsCategories。每个都有一个从 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);

我然后return结果通过ActiveDataProvider

$dataProvider = new ActiveDataProvider(
            [
                'query' => $archivedItemsQuery,
        ]
    ]);
return $dataProvider->getModels();

问题是,当我尝试在请求中发送分页数据,或通过 ActiveDataProvider 进行设置时,没有发生分页。我当然可以将此查询更改为

$unionQuery = (new \yii\db\Query())
                ->from(['counter_items' => $archivedItemsQuery]);

这会产生正确的分页,但我没有得到 ActiveRecords 的结果。

关于如何使用 1 创建联合查询的任何想法。分页工作和 2。结果是 ActiveRecord.

您好,您可以尝试以下方法吗,不是最简洁的方法,但我希望它对您有用,我在最后测试了它,如果我理解正确,您希望 $dataProvider->getModels() 的结果为 return 一个 ActiveRecord 模型对象,即 Products 模型,并希望 GridView 分页同时正常工作。

您需要按以下方式更改 ActiveDataProvider 以使用联合 $archivedItemsQuery

$dataProvider = new \yii\data\ActiveDataProvider([
    'query' => Products::find()->from(['products' => $archivedItemsQuery]),
    'pagination' => [
        'pageSize' => 10,
    ],
]);