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?

Laravelで複数のレコードを更新(バルクアップデート)する方法

Last updated at Posted at 2025-02-01

バルクアップデートとは

複数のレコードを一括で更新すること

前提条件

PHP 8.3
Laravel 11.4

実際のコード

リクエストデータは下記のような感じ
array (
  0 => 
  array (
    'id' => 1,
    'target_column' => 'data',
  ),
  1 => 
  array (
    'id' => 2,
    'target_column' => 'data',
  ),
)
バルクアップデート処理
    public function bulkUpdate(array $data): bool
    {
        $ids       = [];
        $bindings  = [];
        $caseSql   = "CASE ";
        
        try {
            DB::beginTransaction();
            
            foreach ($saveData as $data) {
                $id         = intval($data['id']);
                $caseSql   .= "WHEN id = ? THEN ? ";
                $bindings[] = $id;
                $bindings[] = strval($data['target_column']);
                $ids[]      = $id;
            }
            
            // SQL文を作成
            $placeholders = implode(',', array_fill(0, count($ids), '?'));
            $updateSql    = "UPDATE table_name SET target_column = $caseSql END WHERE id IN (" . $placeholders . ")";
            $bindings     = array_merge($bindings, $ids);
            
            // バルクアップデート
            $result = DB::statement($updateSql, $bindings);
        
            DB::commit();
            return $result;
        } catch (\Exception $e) {
            DB::rollBack();
            throw $e;
        }
    }

最後に

もっと良いコードがあったらコメントで教えて

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?