I have cases, cases_judges, judges and witness tables. A case can have many judges and witness I want to be able to select all the judges and witness associated to a case I don't know how to create a relationship between case and judges because their is no direct link between judges and case. Cases_judges is the only intermediary between case and judge. I also tried using Hasmanythrough relationship but without success
Cases model
public function case_judges(){
return $this->hasMany(Cases_judges::class,'case_id','id');
}
public function witness(){
return $this->hasMany(Witness::class,'case_id','id');
}
public function judges(){
return $this->hasManyThrough(Judges::class, Case_judge::class,'judge_id','id');
}
Judges model
public function judges(){
return $this->hasMany(Case_judge::class,'case_id','id');
}
Cases_judge model
public function case(){
return $this->belongsTo(Cases::class);
}
Cases Controller My case controller is something like this public function index() {
return Cases::with('case_judge','witness')->get();
}
The simplified diagram highlights the connection between your Case
and Judge
models via an intermediate CaseJudge
model. Indeed, a Case
really can have multiple Judge
s. However, we must not miss out the fact that a Judge
can handle multiple Case
s.
From this, we can conclude that Case
and Judge
models have a many-to-many relationship.
To establish a many-to-many relationship between models in Laravel, you must use belongsToMany
relationship method, as opposed to hasManyThrough
which only applies to one-to-many relationship.
class Cases extends Model {
...
public function judges() {
return $this->belongsToMany(Judges::class, 'case_judges', 'case_id', 'judge_id');
}
}
Here, belongsToMany
has four arguments:
- Model that has the many-to-many relationship with our
Cases
model. - Intermediate table connecting tables
cases
andjudges
. - Foregin key on intermediate table that connects to table
cases
. - Foregin key on intermediate table that connects to table
judges
.
When all is set and done, running:
return Cases::with(['judges', 'witness'])->get();
will now return what you want — a collection of cases, along with witnesses and judges associated to their respective cases.
As a side note: you might want to follow Laravel's conventions on naming things, to avoid running into weird default Eloquent behaviors as consequence, and enjoy any conveniences it brings when you conform to these conventions.
CodePudding user response:
I think cases
and judges
are 'Many to Many' relationship with intermediate table cases_judges
.
You can follow this document to setup this : https://laravel.com/docs/9.x/eloquent-relationships#many-to-many