A
A
Alexander Verbitsky2018-03-29 01:41:02
Yii
Alexander Verbitsky, 2018-03-29 01:41:02

Yii2. How to count the number of records received?

There are 2 related tables, products and product_models. The first has 3 records, the second has 4.
The result of the code below, for some reason, is the number of records from the product_models table, i.e. - 4.
And I need count() to read only the quantity from the products table - 3 records.

1. $cat = [1, 2, 3, 15];

2. $query = Products::find()->select('*');

3. $query->innerJoinWith(['productModels']);

4. if ($cat) $query->where(['in', 'product_models.category_id', $cat]);

5. return $query->count();

If you change innerJoinWith to with, it works correctly, but line #4 gives an error (it turns out that it looks for the product_models.category_id column in the products table);
What can be done???
I must say right away that count($query) will not work (due to further calculations)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim Fedorov, 2018-03-29
@VerbAlexVlad

$query->distinct()->count('product.id');

P
profaller, 2018-03-29
@profaller

Because you don't know how INNER JOIN works.
How about just with or if you need it directly in one request, then joinWith

Products::find()
     ->with('productModels')
     ->andWhere(['in', 'product_models.category_id', $cat])
     ->count()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question