LoginSignup
0
1

More than 1 year has passed since last update.

day15の今日は複数データ(大量データ)をまとめて削除する方法を見ていきます。

Doctrine

<?php

declare(strict_types=1);

use App\Entity\Author;
use App\Entity\Book;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Query\ResultSetMapping;

require __DIR__.'/../vendor/autoload.php';

/** @var EntityManagerInterface $entityManager */
$entityManager = require __DIR__.'/bootstrap.php';

// エンティティを使ってやる
foreach ($entityManager->getRepository(Book::class)->findAll() as $book) {
    $entityManager->remove($book);
}
$entityManager->flush(); // begin + 全件のdelete + commitがここで行われる

// エンティティを使えないぐらい多い件数を扱う場合
$conn = $entityManager->getConnection();
$conn->beginTransaction();
for ($i = 1; $i <= 1000000; $i++) {
    $conn->delete('books', ['id' => $i]);
}
$conn->commit();

https://github.com/77web/doctrine-vs-eloquent/blob/3f3119288d597aa035accb364a49ddf221c0ec9b/Doctrine/Usecase/batch_delete.php

  • エンティティのインスタンスを作ることを許容できる場合、通常のEntityManagerを使った削除で十分です。DELETE文はEntityManager::flush()を呼んだときにトランザクション付きでまとめて実行されます。
  • エンティティのインスタンスを作ることが許容できないぐらい大量のバッチ削除を行いたい場合はDBALのConnectionに対する delete() メソッドで実行することもできます。

Eloquent

<?php

declare(strict_types=1);

use App\Models\Book;
use Illuminate\Support\Facades\DB;

require __DIR__.'/../vendor/autoload.php';
require __DIR__.'/bootstrap.php';

DB::beginTransaction();
for ($i = 1; $i <= 100000; $i++) {
    DB::delete('DELETE FROM books WHERE id = ?', [$i]);
}
DB::commit();

https://github.com/77web/doctrine-vs-eloquent/blob/3f3119288d597aa035accb364a49ddf221c0ec9b/Eloquent/Usecase/batch_delete.php

  • insert, updateと同様、モデルに対してバッチ削除をするにはサードパーティのプラグインパッケージが必要です。
0
1
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
1