首页 > 解决方案 > (Laravel)如何在模型中关联外键的外键

问题描述

我有 3 个包含此字段的表:

User:
id
name
address

Employee:
id
user_id

Profile:
id
employee_id

我如何user->nameProfile模型中关联

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

user()函数显然是错误的,我试图从Profile. 这样做的正确方法是什么?

标签: phplaravellaravel-5

解决方案


在两个模型中都设置为belongsTo 。Profile 属于和属于Employee_EmployeeUser

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

在您的控制器中,您可以使用这样的配置文件获取用户数据。

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

推荐阅读