I
I
Igor2017-02-21 11:54:01
Laravel
Igor, 2017-02-21 11:54:01

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 belongsToManywith 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);
}

It is worth considering that when creating new models, you will also have to prescribe additional each time. attributes for pivot fields.
2 . Create a PK and work with links hasManyfor 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');
}

3. Your solution?
Thank you.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question