Answer the question
In order to leave comments, you need to log in
More than two foreign keys in a join table?
Hello! I have several models in the application: works (Work), parts (Part) and stages (Step). In order to know at what stage and for which parts the work is applied, there is a table part_step_work
, it contains only 3 fields, and all 3 fields are foreign keys to the tables of those models that I listed above. Question - how do you act in this situation:
1 . Leave only foreign keys and do not create an auto-increment field id
. Further work occurs only through the connection belongsToMany
with setting the wherePivot condition for the third field. Those. each model will describe the behavior for selecting relationships. Example for model Part
:
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function works() :\Illuminate\Database\Eloquent\Relations\BelongsToMany
{
return $this->belongsToMany(\App\Models\Repair\Work::class, 'part_step_work', 'partId', 'workId')
->withPivot('stepId');
}
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function steps() :\Illuminate\Database\Eloquent\Relations\BelongsToMany
{
return $this->belongsToMany(\App\Models\Repair\Step::class, 'part_step_work', 'partId', 'stepId')
->withPivot('workId');
}
public function worksOfStep($step) :\Illuminate\Database\Eloquent\Relations\BelongsToMany
{
$step = ($step instanceof \Illuminate\Database\Eloquent\Model) ? $step->getKey() : $step;
return $this->works()->wherePivot('stepId', $step);
}
hasMany
for each model. Example for Part
:/**
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function worksOnSteps() :\Illuminate\Database\Eloquent\Relations\HasMany
{
return $this->hasMany(\App\Models\Pivot\PartStepWork::class, 'partId');
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question