0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

TypeORM テーブル全件削除(TRUNCATE、レコードのみ)削除する方法

Last updated at Posted at 2022-07-15

TypeORMでテーブルのレコード削除をする際、大量のレコードを全て削除したい場合があると思います。
その際、以下のコードで実現可能です。

削除したいテーブル(Entity)のクラス名を仮に"TestEntity"とします

他のテーブル(Entity)と外部参照がないテーブルにおいては以下のclear()が使えます
これがSQLのTRUNCATE TABLEにあたります。

connection.createQueryRunner()
.manager.clear(TestEntity)

外部参照キーが設定されている場合は、TRUNCATEできないため、代わりにdelete().from()を使います。

connection.createQueryBuilder()
  .delete()
  .from(TestEntity)
  .execute()

これで全件削除完了です。delete().from()を使って削除する場合は、DBのスペックに処理時間が依存しますので、その点だけご注意ください。

-参考記事-
Delete using Query Builder

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?