【发布时间】:2019-08-02 12:51:10
【问题描述】:
我正在尝试使用 Laravel 5.8 为“用户”表创建外键。
Laravel 5.8 自动生成的迁移表如下,
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
然后从我的“存储库”表中我引用“用户”表如下,
Schema::create('repositories', function (Blueprint $table) {
$table->string('id', 8)->primary();
$table->string('name')->nullable(false);
$table->string('size')->nullable(false);
$table->unsignedInteger('user_id')->nullable(false);
$table->timestamps();
});
Schema::table('repositories', function (Blueprint $table) {
$table->foreign('user_id')->references('id')->on('users');
});
但我在此代码中收到“一般错误:1215 无法添加外键约束”错误。有很多与这个问题相关的解决方案。
General error: 1215 Cannot add foreign key constraint in laravel
Migration: Cannot add foreign key constraint in laravel
Laravel migration "Cannot add foreign key constraint" error with MySQL database
我已经尝试过上述解决方案。但是我的问题没有解决
【问题讨论】:
-
试试这个
$table->integer('user_id')->nullable()->unsigned(); -
看看stackoverflow.com/a/52902308/5928015 ?如果您使用
bigIncrements,那么您需要相应地处理 -
当您使用语法或功能时,请阅读有关如何使用它的手册。在考虑发布之前,请始终使用谷歌搜索您的问题/问题/目标的许多清晰、简洁和准确的措辞,包括和不包括您的特定字符串/名称,并阅读许多答案。如果您发布问题,请使用一个短语作为标题。但这显然是重复的。 How to Ask 也请用您正在使用的 SQL DBMS 标记问题。
标签: laravel foreign-keys laravel-migrations