Matt McDonald
Matt McDonald

Reputation: 5050

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');
    }
}

Upvotes: 4

Views: 2329

Answers (2)

Ollie
Ollie

Reputation: 51

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();

Upvotes: 0

chester
chester

Reputation: 38

try to load the relation after getting the user:

$user = User::find(1);

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

Upvotes: 1

Related Questions