Laravel 7 向用户添加外键时出错 table
Laravel 7 error when adding foreign key to Users table
使用 Laravel 7 和 MySQL,我正在尝试向 Laravel 身份验证系统生成的用户 table 添加外键...
首先,我创建了新的 table user_type,然后,在另一次迁移中,我尝试将外键添加到用户 table,但随后我收到错误消息。
这里是迁移和错误的要点:https://gist.github.com/jdalri/73cee7a00c513c93afd5186ca27d74a4
我也试过使用
$table->unsignedBigInteger('user_type_id');
$table->foreign('user_type_id')->references('id')->on('user_type');
但出现同样的错误。
谢谢
这是 link 到 Laravel 的文档:https://laravel.com/docs/7.x/migrations#foreign-key-constraints
Schema::table('users', function (Blueprint $table) {
$table->foreignId('user_type_id')->constrained('user_type');
});
AddUserTypeToUsersTable
没有主键
试试这个
Schema::table('users', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('user_type_id');
$table->foreign('user_type_id')->references('id')->on('user_type');
});
$table->unsignedBigInteger('user_type_id')->nullable();
$table->foreign('user_type_id')->references('id')->on('user_type');
之所以可行,是因为从字面上看,错误是在向用户 table 添加内容之前,user_type_id 必须有内容。如果将其设为 null,它会起作用,但这样做不是一个好主意。我建议你如果 user_types 不多,将它们创建为枚举并选择默认值。
您的语法是正确的,但您缺少的是外键没有默认值(存在于 user_type table 中)或其不可为空。这是因为 user_type
table 中没有空值记录,所以如果您使用 php artisan migrate:fresh
重置数据库,这将起作用或使该列可为空。
使用 Laravel 7 和 MySQL,我正在尝试向 Laravel 身份验证系统生成的用户 table 添加外键...
首先,我创建了新的 table user_type,然后,在另一次迁移中,我尝试将外键添加到用户 table,但随后我收到错误消息。
这里是迁移和错误的要点:https://gist.github.com/jdalri/73cee7a00c513c93afd5186ca27d74a4
我也试过使用
$table->unsignedBigInteger('user_type_id');
$table->foreign('user_type_id')->references('id')->on('user_type');
但出现同样的错误。
谢谢
这是 link 到 Laravel 的文档:https://laravel.com/docs/7.x/migrations#foreign-key-constraints
Schema::table('users', function (Blueprint $table) {
$table->foreignId('user_type_id')->constrained('user_type');
});
AddUserTypeToUsersTable
试试这个
Schema::table('users', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('user_type_id');
$table->foreign('user_type_id')->references('id')->on('user_type');
});
$table->unsignedBigInteger('user_type_id')->nullable();
$table->foreign('user_type_id')->references('id')->on('user_type');
之所以可行,是因为从字面上看,错误是在向用户 table 添加内容之前,user_type_id 必须有内容。如果将其设为 null,它会起作用,但这样做不是一个好主意。我建议你如果 user_types 不多,将它们创建为枚举并选择默认值。
您的语法是正确的,但您缺少的是外键没有默认值(存在于 user_type table 中)或其不可为空。这是因为 user_type
table 中没有空值记录,所以如果您使用 php artisan migrate:fresh
重置数据库,这将起作用或使该列可为空。