Php (Laravel)如何关联模型中外键的外键
我有3个带有此字段的表:Php (Laravel)如何关联模型中外键的外键,php,laravel,laravel-5,Php,Laravel,Laravel 5,我有3个带有此字段的表: User: id name address Employee: id user_id Profile: id employee_id 如何将user->name与Profilemodel关联 class Profile extends Model { public function employee() { return $this->belongsTo('App\Employee', 'employee_id');
User:
id
name
address
Employee:
id
user_id
Profile:
id
employee_id
如何将user->name
与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);
}
}
user()
函数显然是错误的,我试图从配置文件中获取用户数据。正确的方法是什么?通过关系使用HasOneThrough
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');
}
}
现在,您可以访问用户名,如
$profile->user->name
您可以在以下laravel官方文档中看到示例用法:
通过关系使用HasOneThrough
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');
}
}
现在,您可以访问用户名,如
$profile->user->name
您可以在以下laravel官方文档中看到示例用法:
在两种型号中,使都属于<代码>配置文件
属于员工
和员工
属于用户
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;
在两种型号中,使都属于<代码>配置文件属于
员工
和员工
属于用户
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;
Use HasOneThrough relationship Use HasOneThrough relationship谢谢您的输入,我试图查询这个,但它给了我一个错误
public function index(){$profile=profile::with('user','employee')->get();dd($profile->user);return view('profile.index');}
SQLSTATE[42S22]:未找到列:1054“字段列表”中的未知列“users.profile”
由于用户表中没有profile列,因此遇到此错误。您必须将关系从配置文件模型加载到用户模型,如profile.user not user.profiles谢谢您的输入,我试图查询此信息,但它给了我一个错误public function index(){$profile=profile::with('user','employee')->get();dd($profile->user);return view('profile.index');}
SQLSTATE[42S22]:找不到列:“字段列表”中的1054未知列“users.profile”
由于用户表中没有profile列,因此遇到此错误。您必须将关系从配置文件模型加载到用户模型,如profile.user而不是user.profile