Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Building ternary relationship using Laravel Eloquent Relationships

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:

enter image description here

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?

like image 599
Alexandre Thebaldi Avatar asked Jan 23 '26 02:01

Alexandre Thebaldi


1 Answers

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.

like image 189
sabau Avatar answered Jan 24 '26 19:01

sabau