【问题标题】:Can't able to truncating tables when seeding in laravel 7在 laravel 7 中播种时无法截断表格
【发布时间】:2022-01-12 05:41:51
【问题描述】:

我在截断表时遇到了 laravel 7 的问题,即使我使用了 FOREIGN_KEY_CHECKS 启用和禁用仍然返回这种类型的错误“语法错误或访问冲突:1701 无法截断外键约束中引用的表”。

方法

DB::statement("SET FOREIGN_KEY_CHECKS=0;");

Artisan::call('db:seed', ["--database" => 'DBNAME', '--force' => true, "--class" => 'StatusTableSeeder']);

DB::statement("SET FOREIGN_KEY_CHECKS=1;");

种子文件 StatusTableSeeder.php

public function run()
{
    \DB::table('statuses')->truncate();
    \DB::table('statuses')->insert(array (
            0 => 
            array (
                'id' => 1,
                'name' => 'Current',
                'type' => 'current',
            ),
            1 => 
            array (
                'id' => 2,
                'name' => 'Resolved',
                'type' => 'resolved',
            ),
       ));
}

我已经将 laravel 版本 6 更新到了 7,这种语法在 laravel 6 中运行良好,但是当我将它更新到 laravel 7 之后,它就可以工作了。如果有人知道它的实际问题是什么

【问题讨论】:

  • 可能是其他表将具有截断表的外键。
  • @DevsiOdedra 是的,但是我有 FOREIGN_KEY_CHECKS=0 它在 laravel 6 中运行良好这个问题只出现在 laravel 7 中
  • 阅读参考手册并研究TRUNCATE 语句是如何真正执行的。你会明白中间 DB 状态是不一致的。

标签: php mysql laravel foreign-keys laravel-7


【解决方案1】:

试试这个:

<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

class StatusTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        Schema::disableForeignKeyConstraints();
        DB::table('statuses')->truncate();
        Schema::enableForeignKeyConstraints();

        // and the rest of your code...
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-20
    • 1970-01-01
    • 2016-01-08
    • 2019-08-23
    • 2019-08-08
    • 2015-10-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多