1
1

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 1 year has passed since last update.

あるコレクション内のインスタンスをまとめて削除したい時

Posted at

はじめに

Laravelにおいて、レコードをすべて削除する方法を少し調べてみました。

環境

Laravel 9.52.16

問題

  • マイグレーションファイルを修正した
  • しかし既存のテスト用レコードとの整合性により、エラーが出る
  • そこで既存のレコードを一旦まとめて削除したい
消したいレコード(一部略)
> $purchase_orders = PurchaseOrder::all();
= Illuminate\Database\Eloquent\Collection {#7242
    all: [
      App\Models\PurchaseOrder {#7259
        id: 2,
        title: "受注テスト",
        purchase_abstract: "受注テストです",
        user_id: 3,
      },
      App\Models\PurchaseOrder {#7260
        id: 3,
        title: "あいうえお",
        purchase_abstract: "あいうおえ",
        user_id: 3,
      },
      App\Models\PurchaseOrder {#7261
        id: 4,
        title: "others purchase orders",
        purchase_abstract: "others purchase orders",
        user_id: 1,
      },

解決法

今回のようなEloquentコレクションに対してはdeleteメソッドを使います。

コレクションとはモデルのインスタンスを格納するコンテナです。

今回の場合は、PurchaseOrderというモデルのインスタンスを複数格納しています。

  • ①各レコードをループで削除する
  • ②クエリビルダを使って一括削除する

全てのレコードを削除する時はバックアップしておきましょう

①各レコードをループで削除する

まず一つ目は、コレクション内の各インスタンスを一つずつ取り出し、deleteメソッドを使う方法です。

foreach($purchase_orders as $purchase_order) {
    $purchase_order->delete();

②クエリビルダで削除する

二つ目はクエリビルダを使用する方法です。

PurchaseOrder::query()->delete();
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?