Eager Loading Disaster?

Well, this design flaw (we perfer to call it a compromise) was made on purpose. Pros we’ve got:

  1. Much simpler code for populating related models. Less mistakes. In 1.1 it was too complicated to fix/enhance. Even simple changes were hard.

  2. Ability to use cross-database queries including noSQL.

  3. Simpler API for end user.

  4. It’s not possible to get wrong results from AR the way softark explained (by using togher and limit / offset).

Of course there are cons:

  1. One more query. Usually it has acceptable performance.

  2. Length of IDs for IN() could be too big. There are limitations on DB side. Counter-argument for that is getting more than a hundred AR models for a single request is already a very bad idea from memory footprint standpoint.

Probably it’s possible to incorporate 1.1-like query strategy in 2.0 but we have no good way to do it in mind so far.

No, you don’t need to. You can use exactly the same query to get the count as well as the data.

Yii (not you, but the framework code) just has to change the “select” part of the 1st query to construct the sql to get the count, as Yii 1.1 did for the CDbCriteria. As a result, count of Yii 2.0 may be lighter and faster than that of Yii 1.1, since you don’t need to include the sql parts for retrieving the related models that are reserved for the 2nd and later queries.

I feel that a single query eager loading could be a good option for a simple HAS_ONE (or BELONGS_TO) relation. I would appreciate it if it would be implemented. But again, thinking about the nested relations, it looks not that simple.

Probably the most difficult thing should be the management of table aliases when we try to implement single query eager loading.

Indeed. Aliases and deep relations are the worst part of it. Makes everything very complicated.

I’m not saying it’s set in stone that Yii won’t ever support another query strategy. If there’s a good solition for it, I’d check it.

For the ‘has-one’ relations you can use following yii2tech/ar-eagerjoin extension. It will populate joined relation without extra SQL query being executed.