Building ternary relationship using Laravel Eloquent Relationships

妖精的绣舞 提交于 2020-06-12 23:58:33

问题


Have three entities:

  • Project
  • Employee
  • Employment

Problem description: Employee can work on many projects and for each he has one employment. I want to have access to all projects and your referred employments of a certain employee.

I'm not sure but the relationship must look like a ternary:

The physical table is not defined yet. So, be free to design (most basic) them.

And my question:

How i can build using Laravel Eloquent Relationships?


回答1:


Basically your four tables will be something like:

employee

  • id
  • ...your fields

project

  • id
  • ...your fields

employments

  • id
  • ...your fields

employee_project

  • employee_id
  • project_id
  • employment_id

You can split the problem in 2 by 2 relations:

class Employee extends Model{
  public function projects(){
    return $this->belongsToMany("Project")
  }

  // Second relation is Optional in this case
  public function employments(){
    return $this->belongsToMany("Employment", 'employee_project')
  }
}

A Project model

class Project extends Model{
  public function employees(){
    return $this->belongsToMany("Employee")
  }

  // Second relation is Optional in this case
  public function employments(){
    return $this->belongsToMany("Employment",'employee_project')
  }
}

A Employment model

class Employment extends Model{
  public function employees(){
    return $this->belongsToMany("Employee")
  }

  public function projects(){
    return $this->belongsToMany("Project")
  }
}

At this point in your controller you can manage your relation, for example if you want to add to $employee, the project with id 1 with the employment with id 2 you can simply

$employee->projects()->attach([1 => ['employment_id' => '2']]);

I hope this answer to your question.

If you need timestamps in your pivot table, add ->withTimesetamps() to your relationships.




回答2:


Employee has Employment

Employment has Project



来源:https://stackoverflow.com/questions/32655167/building-ternary-relationship-using-laravel-eloquent-relationships

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!