How to define 3 way relationship in laravel?

by scotty_walker , in category: PHP Frameworks , 10 days ago

How to define 3 way relationship in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by raven_corwin , 9 days ago

@scotty_walker 

In Laravel, a 3-way relationship can be defined by using a pivot table to establish a many-to-many relationship between three models. This involves creating three models and associated migration files, as well as setting up relationships between the models in the respective model classes.


Here is an example of how you can define a 3-way relationship between three models in Laravel:

  1. Create three models using the following command:
1
2
3
php artisan make:model Model1
php artisan make:model Model2
php artisan make:model Model3


  1. Create migration files for each model to define the structure of the tables in the database:
1
2
3
php artisan make:migration create_model1_table
php artisan make:migration create_model2_table
php artisan make:migration create_model3_table


  1. Define the relationships in the model classes. In each model, use the belongsToMany method to define the relationship with the other two models:


In Model1.php:

1
2
3
4
5
6
7
8
9
public function model2()
{
    return $this->belongsToMany(Model2::class, 'pivot_table_name', 'model1_id', 'model2_id');
}

public function model3()
{
    return $this->belongsToMany(Model3::class, 'pivot_table_name', 'model1_id', 'model3_id');
}


In Model2.php:

1
2
3
4
5
6
7
8
9
public function model1()
{
    return $this->belongsToMany(Model1::class, 'pivot_table_name', 'model2_id', 'model1_id');
}

public function model3()
{
    return $this->belongsToMany(Model3::class, 'pivot_table_name', 'model2_id', 'model3_id');
}


In Model3.php:

1
2
3
4
5
6
7
8
9
public function model1()
{
    return $this->belongsToMany(Model1::class, 'pivot_table_name', 'model3_id', 'model1_id');
}

public function model2()
{
    return $this->belongsToMany(Model2::class, 'pivot_table_name', 'model3_id', 'model2_id');
}


Ensure to replace 'pivot_table_name' with the actual name of the pivot table you will create to store the relationships between the three models.

  1. Create a migration file to define the structure of the pivot table and run the migration:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
php artisan make:migration create_pivot_table

Schema::create('pivot_table_name', function (Blueprint $table) {
    $table->unsignedBigInteger('model1_id');
    $table->unsignedBigInteger('model2_id');
    $table->unsignedBigInteger('model3_id');
    
    $table->foreign('model1_id')->references('id')->on('model1');
    $table->foreign('model2_id')->references('id')->on('model2');
    $table->foreign('model3_id')->references('id')->on('model3');
});


  1. Run the migration to create the tables in the database:
1
php artisan migrate


You have now defined a 3-way relationship between three models in Laravel using a pivot table.