Laravel-多对多关系设置 [英] Laravel - Many To Many Relationship Setup

查看:120
本文介绍了Laravel-多对多关系设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Laravel 5,并试图与我建立全面的联系.

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

我有2张桌子,学生和房间.每个房间可以有很多学生,每个学生可以有很多房间.

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?

推荐答案

是的,您所描述的是多对多关系,为此,您将需要一个数据透视表.

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

您的三个表如下: (这可能与您的实际表不同)

students

id (primary key)
name
age

rooms

id (primary key)
room_size
bedroom_count

注:默认情况下,数据透视表的名称由两个模型名称(以单数形式)按字母顺序组成.因此,在这种情况下:学生+房间= room_student.

room_student(数据透视表)

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

数据透视表迁移:

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

    // ...

RoomStudent模型:

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

这篇关于Laravel-多对多关系设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆