【问题标题】:Yii2 - Union query with Pagination into ActiveRecordYii2 - 将分页合并查询到 ActiveRecord
【发布时间】:2018-02-04 15:16:59
【问题描述】:

我有一个案例,我需要一个 联合查询,同时将最终结果作为 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);

然后我通过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' =&gt;Products::find()-&gt;from(['products' =&gt; $archivedItemsQuery]), 'pagination' =&gt; [ 'pageSize' =&gt; 8, ], ]);

标签: yii yii2


【解决方案1】:

您好,您可以尝试以下方法吗,不是最简洁的方法,但我希望它对您有用即Products 模型并希望GridView 分页同时正常工作。

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

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

【讨论】:

  • 我认为有一种更简洁的方法,但这很有效。非常感谢:)
  • 我不确定,但您可以尝试一次将Products::findBySql($archivedItems-Query-&gt;createCommand()-&gt;rawSql) 用于query 参数吗?我认为它也应该以一种简洁的方式工作,如果它有效,我会更新我的答案,而不是在我的座位上,所以目前无法检查。 @mrateb
猜你喜欢
  • 2015-07-07
  • 2015-11-07
  • 1970-01-01
  • 1970-01-01
  • 2021-11-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-09
相关资源
最近更新 更多