我正在尝试将外键应用于列 user_id,与表 users 的 ID 相关
我已经尝试通过迁移和工作台来完成,但这个错误不断出现:
Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails
这是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();
});
}
最佳答案
似乎您正在更新 users 表而不是 UpdateBooksTable 迁移中的 books 表。
您可能已经在 books 表中有了数据。因此,现有书籍未引用 user_id,这是导致错误的原因。
您可以将 nullable() 添加到 user_id,以便现有图书的 user_id 为空。
class UpdateBooksTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
//Seem you are updating books table. change users to books
Schema::table('users', function (Blueprint $table) {
$table->bigInteger('user_id')->unsigned()->nullable();
$table->foreign('user_id')->references('id')->on('users');
});
}
}
关于php - LARAVEL:MYSQL:违反完整性约束:1452 无法添加或更新子行:外键约束失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56873266/