我在下面添加了我的应用程序的一些代码。它仅显示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
产品地址
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);
}
关系函数应返回ActiveQuery
对象:
/**
* @return \yii\db\ActiveQuery
**/
public function getProducts() {
return $all_products = $this->hasMany(Product::className(), ['product_category_id' => 'id']);
}
并且不要在这样的函数(声明关系)中添加任何其他条件和语句,您将可以在ActiveQuery::link()
和其他方法中使用它。
您可以在其他功能中重用您的关系
这是按城市过滤结果的选项
/**
* @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
。
中的第二个参数joinWith
禁用急切加载,以避免对数据库进行不必要的附加查询。
您不应选择完整的相关记录集来获取其计数,而应使用ActiveQuery::count()
function:
/**
* @param City|null $city get the count for particular city
* @return integer
**/
public function getActiveProductsCount($city = null) {
return $this->getActiveProducts($city)->count();
}
$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,我相信这里不需要获取数组a,$key => $value
因为您不使用$key
希望这可以帮助...
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句