未创建外键

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了未创建外键相关的知识,希望对你有一定的参考价值。

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

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

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

            );
        

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

答案

尝试一下

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

            );
        

以上是关于未创建外键的主要内容,如果未能解决你的问题,请参考以下文章

vs Dataset DataTable 中未显示外键列

外键未填充主键值

HSQLDB 无法删除未找到的外键约束对象

HIbernate 一对一注释未在依赖表中生成外键 GerericGenerator

SQL 表未生成

MySql如何创建外键