我有2张桌子。
category (id, name, description, keywords, visibility)
orders (id, category_id, price_id, name, telephone, date, processed)
模型类别
public static function tableName()
{
return 'category';
}
public function getOrders()
{
return $this->hasMany(Orders::className(), ['category_id' => 'id']);
}
function getPrices()
{
return $this->hasMany(Price::className(), ['category_id' => 'id']);
}
和模型订单
public static function tableName()
{
return 'orders';
}
public function getCategory()
{
return $this->hasOne(Category::className(), ['id' => 'category_id']);
}
public function getPrice()
{
return $this->hasOne(Price::className(), ['id' => 'price_id']);
}
我想在显示统计数据类别时显示每个类别的订单数量。怎么做?
树构建代码
<?php foreach ($cat as $item) :?>
<ul class="treeview">
<?php if ($item['id'] != 17): ?>
<li><a href="#"><?=$item['name']?> - 3</a>
<ul>
<?php foreach ($price as $itemok) :?>
<?php if ($item['id'] == $itemok['category_id']): ?>
<li><a href="#"><?=$itemok['name']?></a></li>
<?php endif; ?>
<?php endforeach; ?>
</ul>
</li>
<?php endif; ?>
</ul>
<?php endforeach; ?>
答案 0 :(得分:1)
您可以通过多种方式查看以下示例
$categories = Category::find()->all();
foreach($categories as $category){
echo count($category->orders);
echo $category->getOrders()->count();
}
或在模型类别
中创建单独的方法public function getOrderCount(){
return $this->getOrders()->count();
}
然后像
一样使用它$category->orderCount;