【问题标题】:Foreign key constraint is incorrectly formed laravel 6外键约束的格式不正确 laravel 6
【发布时间】:2020-04-15 18:47:07
【问题描述】:

我有 2 个表,当我尝试迁移时返回给我这个错误:

一般错误:1005 Can't create table usee_anbari.#sql-473_21177 (errno: 150 "Foreign key constraint is wrongly form") (SQL: alter table companies add constraint companies_access_id_foreign foreign key (@987654325) @) 在删除级联时引用accesses (id)

这是我的桌子:

public function up()
{
    Schema::create('companies', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name');
        $table->text('address');
        $table->string('tel1');
        $table->string('tel2');
        $table->integer('owner');
        $table->unsignedBigInteger('access_id');
        $table->string('depot_number')->default(2);
        $table->timestamps();


        $table->foreign('access_id')->references('id')->on('accesses')
            ->onDelete('cascade');
    });
}

还有一个:

public function up()
{
    Schema::create('accesses', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('type');
        $table->string('description');
        $table->timestamps();
    });
}

我想念什么?

【问题讨论】:

  • 这就是你的表的创建顺序吗?表accesses 需要存在才能引用它
  • @kerbholz 在我的本地主机中它已成功完成,但在服务器中只是返回此错误,当我想创建公司表时我收到错误
  • 好吧,一个是 bigIncrements,另一个是 unsignedBigInteger,而你必须使用 bigInteger
  • @AlbertoSinigaglia bigIncrementsunsignedBigInteger

标签: mysql database laravel mariadb laravel-6


【解决方案1】:

在您的database/migrations 文件夹中,按名称排序。然后确保create_accesses_tablecreate_companies_table 之前:

【讨论】:

    【解决方案2】:

    我遇到了同样的问题,我在这里描述如何解决它。

    您必须使用unsignedBigInteger 而不是unsignedInteger。见以下代码:

    Schema::create('orders', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->unsignedBigInteger('user_id')->nullable(); // Changed here
        $table->string('ip_address')->nullable();
        $table->string('email')->nullable();
        $table->text('message')->nullable();
        $table->timestamps();
    
        $table->foreign('user_id')
        ->references('id')->on('users')
        ->onDelete('cascade');
    });
    

    您将使用foreign 的地方使用unsignedBigInteger(如果有ID)。如果还不清楚,请发表评论。

    【讨论】:

      猜你喜欢
      • 2017-10-03
      • 2019-07-25
      • 2017-10-04
      • 2018-02-19
      • 2021-05-26
      • 2020-09-24
      • 2019-11-02
      • 2023-03-19
      • 1970-01-01
      相关资源
      最近更新 更多