33

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

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`
))

我查了一下这个错误应该是什么意思,还发现了其他人遇到同样问题的例子,甚至只是与使用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');
}
4

9 回答 9

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

并且有效!</p>

于 2016-02-23T07:30:36.667 回答
45

正如错误所说,您不能截断外键引用的表。删除应该可以工作......

DB::table('some_table')->delete();
于 2015-07-06T12:43:31.483 回答
11

下降前

Schema::disableForeignKeyConstraints();

在关闭运行方法之前

Schema::enableForeignKeyConstraints();
于 2020-03-29T11:47:06.913 回答
7

使用:_ clear_tableEloquent

Model::query()->delete();

使用默认用户模型的示例

User::query()->delete();
于 2017-05-30T04:04:16.960 回答
5

我的角色和权限设置遇到了同样的问题,这就是我所做的,它可以按我的意愿工作。Truncate() 会将增量列重置为 1,但会引发外键错误,而另一方面,删除工作正常但不会重置增量列,所以我在我的 Seeder 文件中执行了以下操作(在我的情况下为 RoleSeeder.php )

1. [删除()方法]

$roles = [];

... // Some foreach statement to prepare an array of data for DB insert()

// Delete and Reset Table
DB::table('roles')->delete();
DB::statement("ALTER TABLE `roles` AUTO_INCREMENT = 1");
// Insert into table
DB::table('roles')->insert($roles);

这将级联附加到角色表的所有其他子表。在我的情况下users_roles表。这样我就避免了禁用和启用外键检查。

2. 要记住的事情/第二种方法 [ truncate() 方法]

如果您不打算删除存储在子表中的所有数据(在我的情况下为 users_roles 表)...您可以使用 truncate() 然后在 DatabaseSeeders.php 文件中禁用并启用外键检查. 当我对此进行测试并且 users_roles 数据完好无损时,受影响角色表上的种子。

//RoleSeeders.php File

$roles = [];

... // Some foreach statement to prepare an array of data for DB insert()

// Truncate Table
DB::table('roles')->truncate();
// Insert into table
DB::table('roles')->insert($roles);

然后在 DatabaseSeeder.php 文件中,你这样做;

public function run()
{
    DB::statement('SET FOREIGN_KEY_CHECKS=0;');

    $this->call([
        RoleSeeder::class,
    ]);

    DB::statement('SET FOREIGN_KEY_CHECKS=1;');
}

但我更喜欢 delete() 方法,因为我不必禁用/启用外键检查

于 2020-10-05T04:08:52.170 回答
3

您可以使用

DB::table('your_table_name')->delete();

清空表,这不会删除表结构。但自动递增 id 不会从初始数字开始。

于 2017-12-06T15:15:39.373 回答
0

你可以把它扔掉。

$table->dropForeign('posts_user_id_foreign');

于 2020-02-28T06:36:35.377 回答
0

我正在使用 Laravel 7.x,这对我有用。不用说它应该只用于开发。要了解更多信息,请在此处查看

DatabaseSeeder.php

    <?php

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        // the Eloquent part and disabling and enabling of foreign keys is only intended for development
        Eloquent::unguard();

        //disable foreign key check for this connection before running seeders
        DB::statement('SET FOREIGN_KEY_CHECKS=0;');

        $this->call(RolesTableSeeder::class);
        $this->call(UsersTableSeeder::class);

        // supposed to only apply to a single connection and reset it's self
        // but I like to explicitly undo what I've done for clarity
        DB::statement('SET FOREIGN_KEY_CHECKS=1;');
    }
}
于 2020-04-13T00:15:11.583 回答
0

这就是每次都对我有用的方法。添加外键时,请务必添加cascade. 语法是这样的

$table->foreign('column')->references('id')->on('table_name')->onDelete('cascade');

确保替换id为适用于您的任何字段。

现在在运行播种之前添加这个而不是trucate

DB::statement('DELETE FROM table_name');

它将删除所有数据。希望这可以帮助。

于 2017-09-23T05:17:28.973 回答