我正在尝试在我的Laravel 8 Job Portal应用程序中获取登录用户的company_id
。我有这些型号:
- 部门
- 用户
- 公司
- 公司简介
User
只能在具有唯一email
的users
表上出现一次。但他可以有多个CompanyProfile
,因为他可以远程工作多个Company
:
以下是型号:
class Department extends Model
{
protected $table = 'departments';
protected $primaryKey = 'id';
protected $fillable = [
'id',
'company_id',
'name',
];
public function company()
{
return $this->belongsTo('AppModelsCompany','company_id');
}
}
class Company extends Model
{
protected $table = 'companies';
protected $primaryKey = 'id';
protected $fillable = [
'id',
'name',
'org_image',
];
public function users()
{
return $this->hasMany('AppModelsUser');
}
public function departments()
{
return $this->hasMany('AppModelsDepartment');
}
}
class User extends Authenticatable
{
protected $hidden = [
'password',
'remember_token',
];
protected $fillable = [
'name',
'first_name',
'other_name',
'last_name',
'username',
'email',
'password',
];
public function profile(){
return $this->hasMany('AppModelsCompanyProfile', 'employee_id');
}
public function company(){
return $this->hasMany('AppModelsCompanyProfile', 'company_id');
}
}
class CompanyProfile extends Model
{
protected $table = 'company_profiles';
protected $primaryKey = 'id';
protected $fillable = [
'id',
'user_id',
'company_id',
'department_id',
'employment_date',
];
}
考虑到company_id
不在User
模型中,如何在DepartmentController
中获得登录的User
的company_id
?
public function index()
{
$departments = Department::where('company_id', ...)->get();
return view('departments.index')->with('departments', $departments);
}
感谢
在这里,您可以使用"hasManyThrough";关系
将用户模型中的公司关系更改为以下
public function company(){
return $this->hasManyThrough('AppModelsCompany', 'AppModelsCompanyProfile');
}
https://laravel.com/docs/8.x/eloquent-relationships#has-许多通过
我对此不确定,但根据场景,我会像这个一样做
public function index()
{
$user_id = Auth::user()->id;
$users_data = User::where('id',$user_id)->with('company')->first();
$company_id = $users_data->company->company_id;
$departments = Department::where('company_id', $company_id)->get();
return view('departments.index')->with('departments', $departments);
}