Mysql
 SQL >> Database >  >> RDS >> Mysql

Costruire una relazione ternaria con le relazioni di Laravel Eloquent

In sostanza le tue quattro tabelle saranno qualcosa del genere:

employee

  • id
  • ...i tuoi campi

project

  • id
  • ...i tuoi campi

employments

  • id
  • ...i tuoi campi

employee_project

  • employee_id
  • project_id
  • employment_id

Puoi scomporre il problema in relazioni due-per-due:

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') } } 

Un model Project:

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') } } 

Un model Employment:

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

A questo punto, nel tuo controller puoi gestire la relazione: ad esempio, se vuoi aggiungere a $employee il progetto con id 1 con l'employment con id 2, puoi semplicemente fare:

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

Spero che questo risponda alla tua domanda.

Se ti servono i timestamp nella tabella pivot, aggiungi ->withTimestamps() alle tue relazioni.