A
A
Alexander Verbitsky2018-08-16 17:06:21
Yii
Alexander Verbitsky, 2018-08-16 17:06:21

Why does the "count()" method show the wrong number of elements???

There are two models, for example "categories" and "products"
a one-to-many relationship hasMany (one category has many products)
And let's say I have only one category, and there are five products of this category
, in theory, design

Categories::find()->joinWith('products')->limit(1)->count();

should display 1 (there is only one category)
But in fact, it displays 5 (by the number of elements in the associated table) if you use with
instead of joinWith , then everything works correctly, but from the outside, you can’t get close to the "products" elements (for example, for sorting or filtering)... Why is this happening, and how to deal with it??

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Bukharev, 2018-08-16
@evgenybuckharev

$query->groupBy(['id']);
ps. Sometimes it is useful to pull out the generated code via createCommand()->rawSql, feed it to the database, and look at the result.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question