A
A
alex4answ2019-05-05 09:41:16
Yii
alex4answ, 2019-05-05 09:41:16

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

1 answer(s)
D
Dmitry, 2019-05-05
@alex4answ

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')

As a result, the product_count will be included in the selection, which can be used. This parameter will store the number of products for each category.
Substitute your values ​​and everything should work.
More information about working with linked data can be found here .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question