【发布时间】:2015-12-19 18:14:16
【问题描述】:
我的代码中有三个模型公司、用户和员工
User
id
name
Company
id
name
Employee
employer_id // foreign key to id on company table
employable_id
employable_type
- 用户可以拥有多家公司作为所有者/董事/总裁
- 用户不能直接拥有任何员工
- 公司只能有一个用户作为所有者/董事/总裁
- 公司可以有很多员工
- 员工可以有一个雇主,即公司
- 员工可以有多个用户或公司作为员工
- 雇主永远是一家公司
- 一个公司作为雇主,可以雇用另一家公司作为雇员或用户作为雇员...
- 因此公司可以与雇员表有两种关系,即作为雇员本身和作为雇主。
- 用户不得直接雇佣任何人
- 用户只能通过公司雇用员工..
我无法弄清楚我可以在这里使用什么样的关系,以便我可以将用户和公司作为雇员,也可以将公司作为雇主。
-- 编辑 我有以下表结构:
Employee Table ->
employer_id' // Only company_id
employee_person_id // user_id
employee_company_id // Company_id as an employee
employee_type // company or person
name // name of company acting as employee or user full name
email // email of company acting as employee or user email
$table->foreign('employer_id')
->references('id')->on('companies')
->onDelete('cascade');
$table->foreign('employee_person_id')
->references('id')->on('users')
->onDelete('cascade');
$table->foreign('employee_company_id')
->references('id')->on('companies')
->onDelete('cascade');
我的员工类有以下方法
class Employee extends Model
{
public function employedBy()
{
return $this->belongsTo(\App\Models\Company::class, 'employer_id');
}
public function employedPerson()
{
return $this->belongsToMany(\App\Models\User::class, 'employee_person_id');
}
public function employedCompany()
{
return $this->belongsToMany(\App\Models\Company::class, 'employee_company_id');
}
}
我的公司有以下方法
class Company extends Method
{
public function employees()
{
return $this->hasMany(\App\Models\Employee::class, 'employer_id');
}
public function employers()
{
return $this->belongsToMany(\App\Models\Employee::class, 'employee_company_id');
}
}
我的用户有以下方法
class User extends Method
{
public function companies()
{
return $this->hasMany(\App\Models\Company::class, 'user_id');
}
public function employers()
{
return $this->belongsToMany(\App\Models\Employee::class, 'employee_person_id');
}
}
好的,现在让我分步解释:
- 公司想雇佣员工(员工可以是任何其他公司或个人)
- 公司通过电子邮件搜索员工
- 已搜索的公司或人员已添加到员工表中
--另外,当我查询我希望同时拥有受雇用户和受雇公司的所有员工时,请建议我通过员工表获取加入用户和公司的列表的方法--
// I want to write something like this
$company->getEmployees() = // to get detail list of employees and companies in one single collection
【问题讨论】:
标签: database-design polymorphism eloquent laravel-5.1