yii2-usuario icon indicating copy to clipboard operation
yii2-usuario copied to clipboard

Proposal: Use `inverseOf` for the relationship between `User` and `Profile`

Open Eseperio opened this issue 9 months ago • 2 comments

Description

Currently, the relationship between User and Profile does not define inverseOf, which can lead to unnecessary additional queries when both entities are accessed in the same context.

This is a common scenario, as many applications frequently retrieve user-related information along with their profile, whether for authentication, permissions, or general user data retrieval.

Benefit

Adding inverseOf to these relationships ensures that when one of the entities (User or Profile) is eagerly loaded, Yii2 will automatically associate the other without requiring an extra query. This improves performance and reduces database load.

Suggested Implementation

In User.php:

public function getProfile()
{
    return $this->hasOne(Profile::class, ['user_id' => 'id'])->inverseOf('user');
}

In Profile.php:

public function getUser()
{
    return $this->hasOne(User::class, ['id' => 'user_id'])->inverseOf('profile');
}

With this change, if User is loaded with Profile using with('profile'), Yii2 will not trigger an additional query to fetch User when accessing $profile->user.

This modification does not alter the current behavior but provides an optimization for relationship handling.

Eseperio avatar Feb 08 '25 13:02 Eseperio

It's ok to me. Did you test it? Submit a PR

maxxer avatar Feb 10 '25 06:02 maxxer

I can, let me find some time. I also want to perform a few things I have in mind and I need everyday, like creating a new type of token and enabling loginByAccessToken

Eseperio avatar Feb 10 '25 08:02 Eseperio