I found out if a model has a relation using HAS_ONE, then it’s always eager-loaded even when we only access the model itself.
eg.
class User extends CActiveRecord {
public function relations()
{
$relations = array();
$relations['profile'] = array(self::HAS_ONE, 'Profile', 'user_id');
return $relations;
}
}
If we call that model in the controller:
$user = User::model()->findByPk(1);
In the trace log, I saw the query joins User with Profile table. Why is it not lazy loaded? The application will access User many times and most of the time we don’t need the Profile data. I thought the Profile will only be retrieved when we explicitly write $user->profile, but it is not. Wouldn’t it better if it’s lazy loaded, or do I miss something here?
It sounds very strange. The related models should always be loaded lazily when you haven’t used ‘with’. The chances are, I believe, you have specified ‘with’ somewhere. Double check your source code and the trace log.