gpt4 book ai didi

mysql - Laravel 5.1 迁移和播种无法截断外键约束中引用的表

转载 作者:IT老高 更新时间:2023-10-28 23:51:46 26 4
gpt4 key购买 nike

我正在尝试运行迁移(见下文)并为数据库播种,但是当我运行时

php artisan migrate --seed

我收到这个错误:

Migration table created successfully.
Migrated: 2015_06_17_100000_create_users_table
Migrated: 2015_06_17_200000_create_password_resets_table
Migrated: 2015_06_17_300000_create_vehicles_table

[Illuminate\Database\QueryException]
SQLSTATE[42000]: Syntax error or access violation: 1701 Cannot truncate a table
referenced in a foreign key constraint (`app`.`vehicles`, CONSTRAINT `vehic
les_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `app`.`users` (`id`
)) (SQL: truncate `users`)

[PDOException]
SQLSTATE[42000]: Syntax error or access violation: 1701 Cannot truncate a table
referenced in a foreign key constraint (`app`.`vehicles`, CONSTRAINT `vehic
les_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `app`.`users` (`id`
))

我查看了这个错误的含义,还发现了 examples其他人遇到同样的问题,甚至只是与使用 MySQL 有关,以及他们的解决方案,但应用:

DB::statement('SET FOREIGN_KEY_CHECKS=0;'); and 
DB::statement('SET FOREIGN_KEY_CHECKS=1;');

在 down() 中似乎不起作用,当我在 MySQL 中运行 describe 时,表看起来是正确的。

迁移已正确命名,以确保首先迁移用户表,然后迁移车辆,以便可以应用外键,正确设置的表表明迁移已运行,但随后发生错误。我删除并重新创建了数据库并再次尝试,结果相同。我也不明白为什么它试图在第一次迁移和数据库种子时截断,我没想到当您尝试运行 php artisan migrate:refresh --seed 时会发生这种情况。

// 2015_06_17_100000_create_users_table.php

class CreateUsersTable extends Migration
{
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('username', 60)->unique();
$table->string('email', 200)->unique();
$table->string('password', 255);
$table->string('role')->default('user');
$table->rememberToken();
$table->timestamps();
});
}
}

public function down()
{
Schema::drop('users');
}

// 2015_06_17_300000_create_vehicles_table.php

class CreateVehiclesTable extends Migration
{
public function up()
{
Schema::create('vehicles', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->string('make');
$table->string('model');
$table->string('year');
$table->string('color');
$table->string('plate');
$table->timestamps();

$table->foreign('user_id')->references('id')->on('users');
});
}
}

public function down()
{
Schema::drop('vehicles');
}

最佳答案

DB::statement('SET FOREIGN_KEY_CHECKS=0;');
App\User::truncate();
DB::statement('SET FOREIGN_KEY_CHECKS=1;');

而且有效!

关于mysql - Laravel 5.1 迁移和播种无法截断外键约束中引用的表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31192207/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com