laravel外部キー設定したテーブルのデータをtruncateしたい


はじめに

データをいったん消去したかったので調べてみると
php artisan db:seedを使ってできるようだったのでやってみた。
備忘録として残しておきます。

環境

  • Laravel8
  • php8

最初に実行したコード(失敗例)

namespace Database\Seeders;
use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {  
        \App\Models\User::truncate();
        \App\Models\Post::truncate();
    }
}

php artisan db:seed 実行後エラー

   Illuminate\Database\QueryException 

  SQLSTATE[42000]: Syntax error or access violation: 1701 Cannot truncate a table referenced in a foreign key constraint (`laravel`.`post`, CONSTRAINT `post_user_id_foreign`) (SQL: truncate table `users`)

  at vendor/laravel/framework/src/Illuminate/Database/Connection.php:678
    674▕         // If an exception occurs when attempting to run a query, we'll format the error
    675▕         // message to include the bindings with SQL, which will make this exception a
    676▕         // lot more helpful to the developer instead of just the database's errors.
    677▕         catch (Exception $e) {
  ➜ 678▕             throw new QueryException(
    679▕                 $query, $this->prepareBindings($bindings), $e
    680▕             );
    681▕         }
    682▕ 

      +11 vendor frames
  12  database/seeders/DatabaseSeeder.php:21
      Illuminate\Database\Eloquent\Model::__callStatic("truncate", [])

      +22 vendor frames
  35  artisan:37
      Illuminate\Foundation\Console\Kernel::handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))

外部キー制約が発生しており、削除できない。(truncateする順番の違いでもない。)

修正

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Schema;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        Schema::disableForeignKeyConstraints(); //外部キーチェックを無効にする
        \App\Models\User::truncate();
        \App\Models\Post::truncate();
        Schema::enableForeignKeyConstraints(); //外部キーチェックを有効にする
    }
}

がっつり参考にさせていただいた記事

Laravelで外部キー制約のあるテーブルを操作する。
laravel マイグレーション

laravelの公式ドキュメントは見返す度、新しい知識が増えるなぁ。