public function afterFind()
{
parent::afterFind();
$this->thumb = $this->mainPhoto->file;
}
public function getMainPhoto()
{
return $this->hasOne(Photo::className(), ['userId' => 'id'])->onCondition('photoType = 1');
}
User::find()->with('getMainPhoto')->all();
When i use this without the $this->thumb … line in my afterFind() method, the correct amount of queries are executed, including this one:
SELECT * FROM `photo` WHERE (`userId` IN ('62', '61', '60', '58', '56', '55', '54')) AND (photoType = 1)
When i add the $this->thumb … line in my afterFind() method, there are 7 more queries (one for each row) executed:
SELECT * FROM `photo` WHERE (`userId` IN ('62', '61', '60', '58', '56', '55', '54')) AND (photoType = 1)
SELECT * FROM `photo` WHERE (`userId`='54') AND (photoType = 1)
SELECT * FROM `photo` WHERE (`userId`='55') AND (photoType = 1)
SELECT * FROM `photo` WHERE (`userId`='56') AND (photoType = 1)
and so on..
That doesn’t seem right i think? It doesn’t recognize that ‘with’ is used here, so it uses lazy loading to load each photo.
Edit:
I want to use this approach because i need to do some extra stuff with the thumb here (show a different picture when mainPhoto->file is empty).
For some reason, this problem is back again since the last update (?). I’m making the join in a scope, placed in xxxxQuery extends ActiveQuery. When i’m using the relation in afterFind() an extra query for the relation is executed (and the join is made as well).
SELECT `user`.* FROM `user` LEFT JOIN `photo` ON (`user`.`id` = `photo`.`userId`) AND (photoType = 1) WHERE (accountStatus = 1 AND accountType <> 3) AND (`user`.`id`='62')