サブテーブルに参照されているテーブルをtruncateする方法


Laravelのシーダーファイルの一番最初に

DB::table('t_order')->truncate();

としたが、消せない。

エラー内容

[Illuminate\Database\QueryException]                                                                                             
  SQLSTATE[0A000]: Feature not supported: 7 ERROR:  cannot truncate a table referenced in a foreign key constraint                 
  DETAIL:  Table "t_order_sub" references "t_order".                                                                             
  HINT:  Truncate table "t_order_sub" at the same time, or use TRUNCATE ... CASCADE. (SQL: truncate "t_order" restart identity)  

他のテーブルで参照されているのでtruncateできません、とのこと。

解決法

DB::table('t_order_sub')->truncate();
DB::table('t_order')->truncate();

先にサブの方を消す。

全体的に使用されていて、サブとか調べてられないとき

DB::statement('TRUNCATE m_category_id CASCADE');

超強力なやつ。
これで紐づけられているテーブルも道連れで全部消される。
が危ないので、本当に気をつけて。