Yii2有很多条件和多个表

时间:2016-07-31 11:49:00

标签: php yii2 many-to-many relational-database

我在下面添加了一些我的应用程序代码。它仅显示product_category名称和属于此product_category的产品数量。它就像一个魅力。但我想再次获得属于某个城市的类别名称及其产品。例如,我想得到属于" Wooden"类别,位于巴库。我认为我必须在我的模型的getActiveProducts()函数中做一些更改。任何帮助表示赞赏。 这些是我的表格:

产品

LoginFrame

PRODUCT_CATEGORY

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

product_adress

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

我的控制器:

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();

最后我的 ProductCategory 模型:

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

1 个答案:

答案 0 :(得分:2)

  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班级中有address班级和Product关系。

    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; ?>
    
  5. ps 我认为您不需要在控制器中设置joinWith(如果您没有使用它进行进一步查询或eager loading),选择所有类别:

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

    p.p.s。我相信这里不需要获取数组$key => $value因为你没有使用$key

    希望这会有所帮助......