I have several models in the application: works ( Work ), spare parts ( Part ) and stages ( Step ). In order to know at what stage and for which parts the works are used there is a part_step_work table, it contains only 3 fields, and all 3 fields are foreign keys on the tables of those models that I listed above. The question is - what do you do in this situation? Below are my options:
1. Leave only foreign keys and do not create an auto-increment id field. Further, the work occurs only through the belongsToMany connection with the specification of the wherePivot condition for the third field. Those. each model will describe the behavior for selecting links. Example for Part model:
/** * @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'); } /** * @param \Illuminate\Database\Eloquent\Model|int $step * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany */ 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); } It is worth considering that when creating new models, you will also have to prescribe additional each time. attributes for pivot fields. For example, $this->works()->attach(1, ['stepId' => 1]) .
2 Create a PK and work with a hasMany connection 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'); }