Laravel 8.x, 3 models and many to many relationship

Viewed 184

I am new to laravel and trying the following:

I have these tables:

disciplines: id | name

specialties: id | name

categories: id | name

discipline_specialty (pivot table): id | discipline_id | specialties_id

Discipline model:

public function specialties()
    {
        return $this->belongsToMany(Specialty::class);
    }

Specialty model:

public function disciplines()
    {
        return $this->belongsToMany(Discipline::class);
    }

My question is:

how can I relate (many to many) the categories to the pivot table discipline_specialty in order to access the category name with the discipline and specialty ids? I had thought of an additional pivot table that linked category id and discipline_specialty id but I don't know if it's the best solution and how to do it. Do you have any suggestions? Any help is appreciated.

1 Answers

You can introduce a junction/pivot model that will relate these 3 relations as many-to-one/belongsTo and one-to-many/hasMany from Discipline/Speciality/Category.

Discipline       Speciality     Category
    \\              ||             //
     \\             ||            //
      DisciplineSpecialityCategory

This DisciplineSpecialityCategory model will have following attributes or FKs

Table: discipline_speciality_category

  • discipline_id
  • speciality_id
  • category_id

Now you model definitions will be like

class Discipline extends Model
{
    public function disciplineSpecialityCategory()
    {
        return $this->hasMany(DisciplineSpecialityCategory::class, 'id', 'discipline_id');
    }
}

class Speciality extends Model
{
    public function disciplineSpecialityCategory()
    {
        return $this->hasMany(DisciplineSpecialityCategory::class, 'id', 'speciality_id');
    }
}

class Category extends Model
{
    public function disciplineSpecialityCategory()
    {
        return $this->hasMany(DisciplineSpecialityCategory::class, 'id', 'category_id');
    }
}

class DisciplineSpecialityCategory extends Model
{
    public function discipline()
    {
        return $this->belongsTo(Discipline::class, 'id', 'discipline_id');
    }
    public function speciality()
    {
        return $this->belongsTo(Speciality::class, 'id', 'speciality_id');
    }
    public function category()
    {
        return $this->belongsTo(Category::class, 'id', 'category_id');
    }
}
Related