繁体   English   中英

Yii2有很多条件和多个表

[英]Yii2 hasmany condition and multiple table

我在下面添加了我的应用程序的一些代码。 它仅显示product_category名称和属于该product_category的产品数。 它像一种魅力。 但是我想再次获得类别名称及其仅属于特定城市的产品。 例如,我想获取属于“木制”类别并且位于巴库的产品数量。 我认为我必须在模型的getActiveProducts()函数中进行一些更改。 任何帮助表示赞赏。 这些是我的表:

产品

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

产品分类

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; ?>

最后是我的ProductCategory模型:

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. 关系函数应返回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; } 

    假设您在Product类别中具有City类别和address关系。

    joinWith第二个参数禁用急切加载,以避免对数据库进行不必要的附加查询。

  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 (如果您不将其用于进一步的查询或渴望加载 ),只需选择所有类别:

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

pps,我相信这里不需要获取数组$key => $value因为您不使用$key

希望这可以帮助...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM