【问题标题】:Laravel - Many To Many Relationship SetupLaravel - 多对多关系设置
【发布时间】:2018-04-25 07:47:43
【问题描述】:

我正在使用 Laravel 5 并且正在尝试了解我的关系。

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

这会是双向的多对多关系吗?我需要一个数据透视表来实现这一点吗?

【问题讨论】:

    标签: laravel


    【解决方案1】:

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

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

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

    Room 和 Student 型号:

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

    【讨论】:

      【解决方案2】:

      这会是双向的多对多关系吗?

      是的,您需要双向的多对多关系

      我需要一个数据透视表来实现这一点吗?

      是的

      你可以看到更多关于多对多关系here

      【讨论】:

        【解决方案3】:

        是的,您可以实现多对多关系,并且您肯定需要数据透视表来实现多对多关系。 在这种情况下,您可以创建像 room_student 这样的数据透视表,并在其中添加 room_id 和 student_id 列。然后只需在模型中使用 belongsToMany 方法定义关系,并记住在要附加功能的任何地方使用 attach 方法。

        【讨论】:

          【解决方案4】:

          您需要一个数据透视表。

          关于这一点,您可以从这里了解更多信息:

          ManyToManyRelationship

          【讨论】:

            猜你喜欢
            • 2015-12-20
            • 2013-05-13
            • 2018-06-15
            • 2018-01-22
            • 2016-02-26
            • 2016-01-04
            • 2018-07-04
            • 1970-01-01
            相关资源
            最近更新 更多