How make AR relation not execute it's Query default?

I have my User class extending ActiveRecord and implementing IdentityInterface and loading it into the Yii::$app->user component.

When I define a relationship in my class like this:


public function getRole()

    {

        return $this->hasOne(UserRoleRecord::className(), ['id' => 'userroleId']);

    }

Everytime I run a page load the following Query will be executed:


SELECT * FROM userroles WHERE id = X

This is with me not running Yii::$app->user->identity->role

I’ve modified my “findIdentity()” function to make the join directly to avoid running this extra Query.


return static::find()->where(['users.id' => $id])->joinWith('role')->limit(1)->one();

But the relationship Query seem to run every time anyways. Is there a way around this (without removing the relationship "hasOne" method of course and just run the joinWith())? I would be cool for consitency to keep all relationships defined in my Model. But if I have some Models with a couple of relationships the Queries keep adding up.

Any ideas? Cheers

… too add to my own topic. Imagine you run a query on a ActiveRecord for display a list of X users and in this list you want to display the user relation value (in my example the "User role").

For every row you’ll get +1 query to fetch the user role, when you can make this in the initial JOIN.

Maybe I’m just using ActiveRecord wrong?

Thanks

I believe this is by design and it’s me just using the function wrong. What I’m doing now is keeping the relationship and just using it for a single User record.

When I want to display a list of users and their “user roles” I’ll just run a separate ActiveRecord query with it’s own join and fetching it’s own values to ensure I don’t need to use the build in ActiveRecord relationship.

Like this:


User::find()->select(options)->leftJoin('userroles', 'userroles.id = users.userroleId')->where(options)->all();