0

我正在尝试在 Laravel 中创建外键,但是当我使用 artisan 迁移我的表时,我抛出了以下错误:

SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `users` add constraint `users_ent_id_foreign` foreign key (`ent_id`) references `id_ent` (`entreprises`))

我的“企业”迁移代码

 public function up()
{
    Schema::create('entreprises', function (Blueprint $table) {
        $table->engine = 'InnoDB';
        $table->increments('id_ent');
        $table->string('name');
        $table->string('numSiret', 14)->unique();
        $table->integer('nbr_couvert')->length(10);
        $table->timestamps();
    });
}

我的“用户”迁移代码


    public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->engine = 'InnoDB';
        $table->increments('id_user');
        $table->string('log');
        $table->string('name', 45);
        $table->string('firstName', 45);
        $table->string('email')->unique();
        $table->timestamp('email_verified_at')->nullable();
        $table->string('password');
        $table->rememberToken();
        $table->string('num_phone', 20);
        $table->datetime('created_at');
        $table->unsignedInteger('ent_id');
        $table->integer('agenda_id')->nullable();
        $table->tinyInteger('droitUser')->nullable();
        $table->boolean('validateMail');
        $table->string('key', 255);
    });

    Schema::table('users', function ($table) {
        $table->foreign('ent_id')
            ->references('entreprises') //here 
            ->on('id_ent'); //and here
    });

我更改了迁移的顺序,并且在“用户”表之前创建了“企业”表。

我从这里这里尝试了所有解决方案,它们没有什么可改变的。

有人有什么建议吗?

编辑解决方案

真可耻...当我引用我想引用的表格时,我只是犯了一个愚蠢的错误...现在一切都很好...对不起

4

2 回答 2

0

你用的是sqlite数据库吗?如果是这样,sqlite 数据库默认禁用外键功能。

SQLite 默认禁用外键约束。使用 SQLite 时,请确保在您的数据库配置中启用外键支持,然后再尝试在迁移中创建它们。

您可以在此处检查以在 sqlite 数据库中启用外键。

于 2020-02-05T02:24:09.280 回答
0
Schema::create('posts', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->bigInteger('user_id')->unsigned();
            $table->string('title');
            $table->string('slug')->unique();
            $table->string('image')->default('default.png');
            $table->string('zip');
            $table->text('body');
            $table->integer('view_count')->default(0);
            $table->boolean('status')->default(false);
            $table->boolean('is_approved')->default(false);
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->timestamps();
于 2020-02-05T02:26:55.353 回答