【问题标题】:Laravel 5.5 Migrations: cannot create foreign keyLaravel 5.5 迁移:无法创建外键
【发布时间】:2018-02-02 04:48:53
【问题描述】:

所以我有三个表。客户/站点/用户。客户有许多站点。一个客户有很多用户。用户/站点属于客户。很直接。遗憾的是,我们正在从认为使用字符串键是个好主意的人那里导入站点/客户端表的信息。

这是我的迁移 -

这是客户表:

Schema::create('clients', function (Blueprint $table) {
    $table->string('id', 25)->primary();
    $table->char('number', 6)->unique();
    $table->string('name', 50)->unique();
    $table->timestamps();
});

这是网站表:

public function up()
{
    Schema::create('sites', function (Blueprint $table) {
        $table->string('id', 25)->primary();
        $table->string('name', 30)->unique();
        $table->string('number', 10)->unique();
        $table->string('address_1', 60);
        $table->string('address_2', 60)->nullable();
        $table->string('city', 30);
        $table->string('state', 3);
        $table->string('postal_code', 10);
        $table->string('country', 30);
        $table->string('weather_code')->nullable();
        $table->decimal('dimension', 18, 0)->nullable();
        $table->string('dimension_uom', 10)->nullable();
        $table->string('client_id', 25);
        $table->softDeletes();            
        $table->timestamps();

        // Belongs To Client
        $table->foreign('client_id')->references('id')->on('clients');
    });
}

这是用户表:

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('email')->unique();
        $table->string('password');
        $table->string('client_id', 25);
        $table->rememberToken();
        $table->timestamps();

        // Belongs To Client
        $table->foreign('client_id')->references('id')->on('clients');
    });
}

但是,当我运行这些时,我收到以下错误:

SQLSTATE[HY000]:一般错误:1215 无法添加外键约束(SQL:alter table users 添加约束users_client_id_foreign 外键(client_id)引用clientsid))

SQLSTATE[HY000]:一般错误:1215 无法添加外键约束

如果我删除了对用户的外键尝试,但将其保留在站点中,它可以正常工作。我在两者中都在做完全相同的事情,但由于某种原因它在网站中而不是在用户中有效。知道为什么吗?

【问题讨论】:

  • 您使用的是哪个数据库?

标签: laravel laravel-5.5


【解决方案1】:

这里的问题是,当您运行迁移 user 表时,首先创建了表,然后找不到 client 表,然后它会发出声音。因此,请确保在 users 之前运行 clients 迁移。更改时间戳。

  1. 客户端迁移优先

  2. 用户迁移后

【讨论】:

  • 就是这样。哇,我觉得自己好傻。是在应用程序开发的开始,所以我想 id 去修改原始迁移而不是创建新迁移.....没有考虑顺序。感谢您的帮助!
  • 很高兴它有帮助:) ...确保接受@BillGarrison 的答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-08-16
  • 2016-11-20
  • 2023-01-04
  • 2021-12-31
  • 2018-03-06
  • 2016-02-11
  • 2018-04-24
相关资源
最近更新 更多