简体   繁体   中英

Laravel hasOne conditional relationship

I have a User model and each user has a type of either internal or external. The data stored on internal and external users is very different so there are separate UserInternal and UserExternal models.

How can I define this relationship? There's a key 'user_id' in the UserInternal and UserExternal tables, and each user will have a matching row in one of the tables.

When I retrieve user data it's always via the User model, but I then want the extended data.

How would I go about doing it? I tried this, but it doesn't always work (for example if I try User::with('data') -> find(1) it won't work because $this won't be set yet.

Within User model:

public function data()
{
    if( $this -> type === 'internal' )
    {
        return $this -> hasOne('UserInternal');
    }
    else
    {
        return $this -> hasOne('UserExternal');
    }
}

try to load the relation after getting the user:

$user = User::find(1);

if( ! is_null($user))
{
    $user->load('data');
}

I don't think you can chain find() after anything else in an Eloquent model.

An alternative opposed to the other answer would be:

User::with('data')->where('user_id', 1)->first();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM