Hi all,
I try to convert my Yii 1 code to Yii 2 and encountered a problem. Maybe you can help:
I have two ActiveRecord models: "News" and "NewsContent" with "News hasMany NewsContent". The relation works well. But now I want to create an ActiveDataProvider for News which should eager load NewsContent but only select a few fields of NewsContent to reduce the amount of data transferred. In Yii 1 I did the following:
$provider = new CActiveDataProvider('News', array(
'criteria'=>array(
'select' => 'created',
'condition' => 'published=1',
'order' => 'created DESC',
'with' => array('contents'=>array(
'select' => array(
'title',
'intro',
),
'on' => 'contents.language=:lang',
'params' => array(':lang' => Yii::app()->language)
)),
),
'pagination'=>array(
'pageSize'=>20
),
));
Now I tried the following in Yii 2:
$query = News::find()
->select(['news.id', 'news.created'])
->where(['published' => 1])
->orderBy(['created' => SORT_DESC])
->joinWith([
'newsContents' => function ($query) {
// TODO $query->select(['news_content.id', 'news_content.title', 'news_content.intro']);
$query->onCondition(['news_content.language' => \Yii::$app->language]);
}
]);
$provider = new ActiveDataProvider([
'query' => $query,
'pagination' => [
'pageSize' => 20,
],
]);
This works so far: News and NewsContent are loaded using two SQL-queries (one SELECT for the News and one SELECT for the NewsContents).
However if I include the line marked with the "TODO" to limit the fields which should be selected, then no NewsContents are loaded. But the Yii Debugger Bar states that the correct queries were executed: two SELECT statements (one for News and one for NewsContent with only id, title and intro selected).
Am I doing something wrong or is there a bug with populating the models?