我有一个列为的表User
$table->increments('id');
$table->string('emp_id');
$table->string('email')->unique();
$table->string('password');
和表员工
$table->increments('id');
$table->string('employee_id')->unique();
$table->string('employee_name');
$table->string('department');
$table->string('designation');
$table->string('supervisor');
$table->string('hr_master');
$table->timestamps();
当我第一次使用JWT登录时,我有emp_id from User是Employee表的外键。我想在User表中使用emp_id查看员工的配置文件,以在employee表中获取该员工的信息。这是我写的功能
public function getEmployeeDetail(){
return $this->user->employee()
->first()->toArray();
}
首先在用户模型中创建关系
public function employee()
{
return $this->hasOne(Employee::class,'emp_id','id');
}
现在称之为
$user=auth()->user();
$user->employee //out put = curent Employee detail
您可以向App/User
模型添加访问器。
public function getEmployeeAttribute()
{
return AppEmployee::find($this->emp_id);
}
之后,您可以访问相关的AppEmployee
数据,如下所示:
$user->employee->employee_name
如果用户与任何员工无关,您可以使用可选的助手功能来防止出现错误:
optional($user->employee)->employee_name