2016-08-18 38 views
0

我有一個網上商店與動態字段(規格)和過濾器。所有規格都存儲在表格中,例如Yii2動態添加joinWith

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')。

在此先感謝。

我也同意不同的desicion。

編輯:

更改查詢與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個產品。

我的錯誤在哪裏?

回答

0

可能是你可以使用andFilterWhere(如果該值就是codntion添加,否則和其中添加空否)

$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]) 
+0

我的問題是不是哪裏的條件。它在我的var $ whereString中。當我循環過濾條件的過濾器在$ whereString連接,但我不能連接所有連接。例如,我有2個過濾器,我需要2個左連接,例如,左加入product_spec作爲prod_spec_1 ON ....左加入product_spec作爲prod_spec_2,所以在我的where條件中我有prod_spec_1.spec_id = filterValue1 AND prod_spec_2.spec_id = filterValue2 – pLe0mAx