我正在尝试将外键应用于与表用户 ID相关的user_id列
我尝试通过迁移和在工作台中执行此操作,并且此错误不断出现:
违反完整性约束:1452无法添加或更新子行:外键约束失败
这是mysql:
ALTER TABLE `dh_booky`.`books`
ADD CONSTRAINT `books_user_id_foreign`
FOREIGN KEY (`user_id`)
REFERENCES `dh_booky`.`users` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION;
第一本迁移书籍:
public function up()
{
Schema::create('books', function (Blueprint $table) {
$table->bigIncrements('id');
$table->bigInteger('title_id')->unsigned();
$table->foreign('title_id')->references('id')->on('titles');
$table->bigInteger('author_id')->unsigned();
$table->foreign('author_id')->references('id')->on('authors');
$table->string('image')->nullable();
});
}
更新迁移书籍:
class UpdateBooksTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->bigInteger('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
//php artisan make:migration update_votes_table
});
用户迁移:
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->timestamps();
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
});
}
在进行books表迁移之前,将用户迁移设置为早期版本。否则,在创建books表时,尚无要引用的用户表,因此会出现错误。
这个第一:
Schema::create('users', function (Blueprint $table) {...}
然后,在创建books表时,用户的外键将有一个表可连接。