简体   繁体   中英

(Laravel) How to associate foreign key of a foreign key in model

I have 3 table with this fields :

User:
id
name
address

Employee:
id
user_id

Profile:
id
employee_id

how can i associate user->name from Profile model

class Profile extends Model
{

    public function employee()
    {
        return $this->belongsTo('App\Employee', 'employee_id');
    }

    public function user()
    {
        return $this->belongsTo('App\User', $employee->user_id);
    }
}

The user() function is obviously wrong, T'm trying to get the user data from the Profile . what is the proper way to do this?

Use HasOneThrough relationship.

class Profile extends Model
{

    public function employee()
    {
        return $this->belongsTo('App\Employee', 'employee_id');
    }
    /**
     * Get the User
     */
     public function user()
     {
        return $this->hasOneThrough('App\User', 'App\Employee');
     }
}

Now, You can access user name like,

$profile->user->name

You can see the example usage in laravel official documentation here:

https://laravel.com/docs/5.8/eloquent-relationships#has-one-through

Make belongsTo in both Model. Profile belong with Employee and Employee belong with User

class Profile extends Model
{

    public function employee()
    {
        return $this->belongsTo('App\Employee', 'employee_id');
    }
}


class Employee extends Model
{

    public function user()
    {
        return $this->belongsTo('App\User', 'user_id');
    }
}

In your controller you can get user data using profile like this.

$profile = Profile::with('employee.user')->first();
echo $profile->employee->user->name;

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