Yii 2 will execute at least 2 queries when you include the relations using "with" or "joinWith". One for the main model and the other for the related models. In other word, the fetching of the main model and that of the related models is cleanly separated.
It’s very natural that you may wonder why. It looks (and is) less effective than the strategy used by Yii 1.1 that fetches both of them in a single query for a standard “has one” relation.
But this change in the design has introduced at least 2 good things:
It enables the relation between a SQL database and a NON SQL database.
It solves the complicated problem regarding "has many" relations.
As for the latter, please take a look at this wiki article:
$categories = Category::find()->with(['stories'])->where( .... )->all();
foreach($categories as $category) {
// The following is not necessary any more
// $stories = Story::find()->where(['category_id' => $category_id])->all();
foreach($category->stories as $story) {
echo $story->title;
}
}
Sorry if I’m wrong, but don’t you misunderstand that “with” and/or “joinWith” work only for “has one” relation? And did you consider using the relations of a related model … I mean, nested relations … ?