Answer the question
In order to leave comments, you need to log in
How to find the number of related records?
Good afternoon, there are categories, and products, in the gridview of categories you need to display the number of products for them.
To do hasMany, only to find out the number is somehow not correct, as it seems to me (pull all the information, instead of count())
Please tell me, how can I find out the number of related records?
Answer the question
In order to leave comments, you need to log in
Here's a query you can make using joinWith().
In the Categories model, we add the public field product_count.
$query = Category::find()
->select(['*', 'product_count' => new \yii\db\Expression('COUNT(products.id)')])
->joinWith('products', false)
->groupBy('{{%categories}}.id')
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question