【发布时间】:2015-12-19 21:08:42
【问题描述】:
我有以下模型关系。如果用户以员工身份登录,我希望他们能够获得其公司的员工列表以及他们被分配的角色:
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');
}
【问题讨论】:
-
您已经将角色作为声明函数,为什么要在 $users 查询中覆盖它?
标签: php mysql sql eloquent laravel-5.1