I have 2 tables.
category (id, name, description, keywords, visibility)
orders (id, category_id, price_id, name, telephone, date, processed)
Model Category
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']);
}
and Model Orders
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']);
}
I want to display the number of orders for each category when displaying categories for statistics. How to do it?
Tree building code
<?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; ?>
There are multiple ways you can do that see the example below
$categories = Category::find()->all();
foreach($categories as $category){
echo count($category->orders);
echo $category->getOrders()->count();
}
or create a separate method inside the model category
public function getOrderCount(){
return $this->getOrders()->count();
}
and then use it like
$category->orderCount;
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments