【问题标题】:Yii2 dynamically add joinWithYii2动态添加joinWith
【发布时间】:2016-12-25 08:27:59
【问题描述】:

我有一个带有动态字段(规范)和过滤器的在线商店。所有规格都存储在表中,例如

product_specifications:
-id
-product_id
-spec_id
-spec_val_id

过滤器与规范相关联,所以当我发送过滤器值时,我发送规范值。例如

$_GET['Filters']['filter_id']['spec_val_id']

当我循环过滤器时,我想将左连接添加到产品查询中。类似的东西

$joinString = "";
foreach($filters){
$joinString .= "LEFT JOIN product_specifications AS prod_'.filter.' ON .....";
}

我对 ActiveDataProvider 有这样的查询:

$prodQuery = Product::find()->joinWith('translation')->joinWith('cats')->[HERE FILTERS JOINS]->where($whereString)->groupBy(['id']);

但如果我有 5 个过滤器,我需要 5 个连接到表 product_specifications。 我可以在 joinWith 中添加一个包含所有连接的数组或向查询链添加 5 个连接吗? 对于一个类别,我的过滤器也是动态的,因此页面可以有 5 或 10 个过滤器,我无法添加静态数量的 joinWith('specs')。

提前致谢。

我也同意不同的决定。

编辑:

我用这样的 findBySql 更改查询

$prodQuery = Product::findBySql('
              SELECT `product`.* 
              FROM `product` 
              LEFT JOIN `productLang` ON `product`.`id` = `productLang`.`product_id` 
              LEFT JOIN `product_cat` ON `product`.`id` = `product_cat`.`product_id` 
              LEFT JOIN `page` ON `product_cat`.`page_id` = `page`.`id` 
              LEFT JOIN `page` `parent` ON `page`.`id_in` = `parent`.`id`'
              .$joinString.
              ' WHERE ( '
                    .$whereString.
                    ' AND (`language`=\''.$lang->url.'\')) GROUP BY `product`.`id` ');

还有我的数据提供者:

$dataProvider = new ActiveDataProvider([
                'query' => $prodQuery,
                'pagination' => [
                    'totalCount' => count($prodQuery->all()),
                    'pageSize' => $pageSize,
                    'route' => Yii::$app->getRequest()->getQueryParam('first_step'),
                ],
                'sort' => [
                    'defaultOrder' => $orderArr,
                ],
            ]);

现在我的问题是分页和排序。在我的测试站点中,我有 4 个产品,当我设置 $pageSize = 1; 时,我有 4 个分页页面,但在每个页面中我都有所有 4 个产品。

我的错误在哪里?

【问题讨论】:

    标签: join yii2 filtering


    【解决方案1】:

    你可以使用andFilterWhere(如果值为null,则不添加任何地方,否则添加andWhere)

    $prodQuery = Product::find()->joinWith('translation')->joinWith('cats')->where($whereString)->groupBy(['id']);
    
    
    $prodQuery->andFilterWhere(['attribute1' => $value1])
              ->andFilterWhere(['attribute2' => $value2])
              ->andFilterWhere(['attribute3' => $value3])
              ->andFilterWhere(['attribute4' => $value4])
              ->andFilterWhere(['attribute5' => $value5])
    

    【讨论】:

    • 我的问题不在于条件。它在我的 var $whereString 中。当我循环过滤器时,过滤器的条件在 $whereString 中连接,但我无法连接所有连接。例如,我有 2 个过滤器,我需要 2 个左连接,例如 LEFT JOIN product_spec as prod_spec_1 ON.... LEFT JOIN product_spec as prod_spec_2,所以在我的 where 条件下,我有 prod_spec_1.spec_id = filterValue1 AND prod_spec_2.spec_id = filterValue2
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-12
    • 1970-01-01
    • 2017-11-12
    • 2016-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多