我有以下模型关系。如果用户以员工身份登录,我希望他们能够获得他们公司的员工列表以及他们被分配的角色:
class User {
// A user can be of an employee user type
public function employee()
{
return $this->hasOne('App\Employee');
}
//
public function roles()
{
return $this->belongsToMany('App\Role');
}
}
class Employee {
// employee profile belong to a user
public function user()
{
return $this->belongsTo('App\User');
}
// employee belongs to a company
public function company()
{
return $this->belongsTo('App\Company');
}
}
class Company {
public function employees()
{
return $this->hasMany('App\Employee');
}
}
但是下面的查询不起作用。我收到错误 Column not found: 1054 Unknown column companies.id in WHERE clause
:
$employee = Auth::user()->employee;
$companyEmployees = Company::with(['employees.user.roles' => function ($query) use ($employee) {
$query->where('companies.id', '=', $employee->company_id)
->orderBy('users.created_at', 'desc');
}])->get();
users表和employees表是一对一的关系。
所有员工都有一个基本角色类型 employee
,此外他们还可能有其他角色,例如 manager
、supervisor
等。
如何编写一个查询,为我提供一家公司及其所有员工及其角色?
我已经尝试向 Company 模型添加 hasManyThrough 关系,但这也不起作用吗?
public function users()
{
return $this->hasManyThrough('App\User', 'App\Employee');
}
最佳答案
我想您是想获取当前用户的同事列表并急切加载用户和角色?
$employee = Auth::user()->employee;
$companyEmployees = Company::with(['employees.user.roles')->find($employee->company_id);
或者也许:
$companyEmployees = Company::find($employee->company_id)->employees()->with('user.roles')->get();
$sorted = $companyEmployees->sortBy(function($employee){ return $employee->user->created_at; });
这可能是一条更直接的路线。您的员工 ID 是否在用户表中,反之亦然? Eloquent 关系很容易倒退。
关于php - Laravel 5.1 Eloquent 查询语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34375432/