A
A
Anton Shelestov2019-03-02 16:00:54
Laravel
Anton Shelestov, 2019-03-02 16:00:54

How to setup relationship with extra field in povit table?

Hello!
Can anyone tell me how to properly set up the relationship in the pivot table for the additional field?
pivot table:
99f0b96d36.png
the department_id column is an add. field

class EduSpeciality extends Model
{
    //
    public function profiles()
    {
        return $this->belongsToMany(Profile::class)
            ->withPivot('department_id');
    }
}

dd($this->eduSpeciality->profiles->toArray());

This code outputs the result:
84ae76e858.png
Here's the actual question of how to set up a relationship with the department_id field?
To then ideally receive information in the following way:
$this->eduSpeciality->profiles->first()->pivot->department->name

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman, 2019-03-02
@procode

your situation is theoretically solved in this way:
https://laravel.ru/docs/v5/eloquent-relationships#hmt
but as far as I understand, the pivot table should have two foreign keys
, that is, if you have three of them, then you need to do two intermediate tables
, well, if it's wise)))
ZY . That is, withPivot(), as far as I understand, serves to manipulate auxiliary fields, such as updated_at, and not to create a pivot table with many foreign keys.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question