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

Laravel,livewire2.0 TipsAdvent Calendar 2022

Day 12

論理削除が存在するテーブルをQuery Builderで取得する際の注意

Last updated at Posted at 2022-12-11

概要

LaravelでのDB操作にはEloquentとQuery Builderがあります。

操作対象のテーブルに論理削除の概念があった場合、QueryBuilderには注意が必要です。

QueryBuilderはデフォでは削除済みデータも含む

DB
1人だけ論理削除します
スクリーンショット 2022-12-05 15.19.32.png

Eloquentで[全て取得、削除済みも含む]
QueryBuilderで[全て取得]
処理を行います

さんぷる
dd([
    'Eloquent:User all' =>  User::all(),
    'Eloquent:User withTrashed' => User::withTrashed()->get(),
    'QueryBuilder:User get' => DB::table('users')->get(),
]);

結果

array:3 [
  "Eloquent:User all" => Illuminate\Database\Eloquent\Collection {#1408 ▼
    #items: array:3 [▶]
    #escapeWhenCastingToString: false
  }
  "Eloquent:User withTrashed" => Illuminate\Database\Eloquent\Collection {#1412 ▼
    #items: array:4 [▶]
    #escapeWhenCastingToString: false
  }
  "QueryBuilder:User get" => Illuminate\Support\Collection {#1179 ▼
    #items: array:4 [▶]
    #escapeWhenCastingToString: false
  }
]

QueryBuilderでdeleted_atに条件指定せずにget()した場合削除済みのデータまで引っ張ってしまいます。

1
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
1
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?