fightstarr20
fightstarr20

Reputation: 12568

Laravel - Many To Many Relationship Setup

I am using Laravel 5 and am trying to get my head round relationships.

I have 2 tables, students and rooms. Each room can have many students, and each student can have many rooms.

Would this be a Many to Many relationship in both directions? Would I need a pivot table to achieve this?

Upvotes: 1

Views: 110

Answers (4)

Jeffrey
Jeffrey

Reputation: 473

Yes, what you describe is a many-to-many relationship, and for that you'll need a pivot table.

Your three tables would look like this: (this might look different from your actual tables)

students

id (primary key)
name
age

rooms

id (primary key)
room_size
bedroom_count

Note: by default, the name of the pivot table is composed of both model names (in singular form), in alphabetical order. So in this case: Student + Room = room_student.

room_student (pivot table)

room_id (foreign key to 'rooms')
student_id (foreign key to 'students')

Pivot table migration:

class CreateRoomStudentTable extends Migration
{
    public function up()
    {
        Schema::create('room_student', function (Blueprint $table) {
            $table->unsignedInteger('room_id');
            $table->unsignedInteger('student_id');

            // Primary key
            $table->primary(['room_id', 'student_id']);

            // Both foreign keys
            $table->foreign('room_id')
                ->references('id')
                ->on('rooms')
                ->onDelete('cascade');
            $table->foreign('student_id')
                ->references('id')
                ->on('students')
                ->onDelete('cascade');
        });
    }

    // ...

Room and Student models:

class Room extends Model {
    // ...
    public function students()
    {
        $this->belongsToMany(App\Student::class);
    }
}

class Student extends Model {
    // ...
    public function rooms()
    {
        $this->belongsToMany(App\Room::class);
    }
}

Upvotes: 1

Radu
Radu

Reputation: 1031

You need a pivot table.

About that, you can find out more from here:

ManyToManyRelationship

Upvotes: 0

Mortada Jafar
Mortada Jafar

Reputation: 3679

Would this be a Many to Many relationship in both directions?

yes you need to Many to Many relationship in both directions

Would I need a pivot table to achieve this?

yes

you can see more about Many to Many relationship here

Upvotes: 1

Chirag Chaudhari
Chirag Chaudhari

Reputation: 1817

Yes you can implement many to many relationship and you will definitely need pivot table for implementing many to many relationship. In this case you can create pivot table like room_student and add the room_id and student_id columns in it. then just use define relationship using belongsToMany method in your models and remember to use the attach method whereever you want to attach the functionality.

Upvotes: 0

Related Questions