2016-07-31 95 views
0

我在下面添加了我的應用程序的一些代碼。它僅顯示屬於此product_category的product_category名稱和產品數量。它像一個魅力。但我想重新獲得僅屬於某個城市的分類名稱及其產品。例如,我想獲得屬於「木製」類別並位於巴庫的產品數量。我認爲我必須對模型的getActiveProducts()函數進行一些更改。任何幫助表示讚賞。 這些都是我的表:Yii2 hasmany條件和多表

產品

id | name  | offer_category_id 
----------------------------- 
1 | Khar  | 3 
2 | SantaCruz | 2 
3 | Furniture | 2 
4 | VT  | 1 
5 | newFort | 4 

PRODUCT_CATEGORY

id | name 
-------------- 
1 | Khar   
2 | Wooden 
3 | Sion  
4 | VT 
5 | newFort 

product_adress

id | city  | offer_id 
----------------------------- 
1 | Baku  | 1 
2 | Ismailly | 2 
3 | Absheron | 5 
4 | Paris  | 4 
5 | Istanbul | 3 

我的控制器:

$data['productCategory'] = ProductCategory::find() 
->joinWith('products') 
->all(); 

查看代碼:

<?php foreach($data['productCategory'] as $key=>$value):    
<li> 
    <span class="m-offer-count"><?= $value->productsCount; ?></span> 
</li> 
<?php endforeach; ?> 

最後我產品分類型號:

public function getActiveProducts() { 
     $all_products = $this->hasMany(Product::className(),['product_category_id' => 'id'])->select(['id'])->where(['status'=>1])->all(); 
     return $all_product; 
} 
public function getProductsCount() { 
     return sizeof($this->activeProducts); 
} 

回答

1
  1. Relation function應該返回ActiveQuery對象:

    /** 
    * @return \yii\db\ActiveQuery 
    **/ 
    public function getProducts() { 
        return $all_products = $this->hasMany(Product::className(), ['product_category_id' => 'id']); 
    } 
    

    而且不會增加這種功能(即宣告關係)的其他條件和聲明,你就可以在這樣的方法如ActiveQuery::link()和其他人使用它。

  2. 您可以重複使用其他功能

    你們的關係在這裏是城市

    /** 
    * @param City|null $city filter result by city 
    * @return \yii\db\ActiveQuery 
    **/ 
    public function getActiveProducts($city = null) { 
        $query = $this->getActiveProducts() 
         ->andWhere(['status' => 1]); 
    
        if (!empty($city)) { 
         $query->joinWith('address', false) 
          ->andWhere(['address.city_id' => $city->id]); 
        } 
    
        return $query; 
    } 
    

    假設你有City類和Productaddress關係過濾結果的選項。

    second parameter in joinWith禁用eager loading可避免不必要的額外查詢到您的數據庫。

  3. 你不應該選擇全套的相關記錄,以獲得他們的數量,使用ActiveQuery::count()函數:

    /** 
    * @param City|null $city get the count for particular city 
    * @return integer 
    **/ 
    public function getActiveProductsCount($city = null) { 
        return $this->getActiveProducts($city)->count(); 
    } 
    
  4. 使用$city過濾器在你看來

    <?php foreach($data['productCategory'] as $category):    
    <li> 
        <span class="m-offer-count"> 
         <?= $category->getActivePoductsCount($city); ?> 
        </span> 
    </li> 
    <?php endforeach; ?> 
    

PS我認爲你不需要做joinWith在你的控制器(如果你不使用它作進一步的查詢或eager loading),只需選擇所有類別:

$data['productCategory'] = ProductCategory::find()->all(); 

p.p.s.我認爲,這裏沒有必要,因爲你不使用$key

希望這有助於獲取數組$key => $value ......

+0

我用另一種方式解決了這個任務,如果你想我心底分享 –

+0

@ShaigKhaligli你可以用你的解決方案更新這個答案。或者更新你的問題。你如何解決這個問題很有意思,並且對別人有幫助 – oakymax