首页 > 解决方案 > 未创建外键

问题描述

我正在尝试在教师表中创建一个外键。迁移后,所有列都在那里,但没有创建外键

首先,我创建了两个表,用户表和课程表。

if(! Schema::hasTable('users')) {
            Schema::create('users', function (Blueprint $table) {
                $table->increments('id');
                $table->string('name');
                $table->string('email');
                $table->string('password');
                $table->string('remember_token')->nullable();

                $table->timestamps();

            });
        }
if(! Schema::hasTable('courses')) {
            Schema::create('courses', function (Blueprint $table) {
                $table->increments('id');
                $table->string('title');
                $table->string('slug')->nullable();
                $table->text('description')->nullable();
                $table->decimal('price', 15, 2)->nullable();
                $table->string('course_image')->nullable();
                $table->date('start_date')->nullable();
                $table->tinyInteger('published')->nullable()->default(0);

                $table->timestamps();
                $table->softDeletes();

                $table->index(['deleted_at']);
            });
        }

然后我用外键创建了另一个名为“老师”的表

if(! Schema::hasTable('teacher')) {
            Schema::create('teacher', function (Blueprint $table) {
                $table->increments('id');
                $table->integer('user_id')->unsigned();
                $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
                $table->integer('course_id')->unsigned();
                $table->foreign('course_id')->references('id')->on('courses')->onDelete('cascade');
                $table->string('teachers_image')->nullable();
                $table->text('education')->nullable();
                $table->text('contact')->nullable();

                $table->timestamps();
                $table->softDeletes();

            });
        }

迁移后我可以看到表在那里,但没有创建外键

标签: phpsqllaravel

解决方案


尝试这个

if(! Schema::hasTable('teacher')) {
            Schema::create('teacher', function (Blueprint $table) {
                $table->increments('id');
                $table->unsignedInteger('user_id');
                $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
                $table->unsignedInteger('course_id');
                $table->foreign('course_id')->references('id')->on('courses')->onDelete('cascade');
                $table->string('teachers_image')->nullable();
                $table->text('education')->nullable();
                $table->text('contact')->nullable();

                $table->timestamps();
                $table->softDeletes();

            });
        }

推荐阅读