0
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.

アップサート処理のテンプレート(Laravel)

Posted at

初めに

Laravelのアップサートを実装したので、コピペ用として残します。
(モデル使用)

環境

開発環境 バージョン
Laravel 10.1.5
PHP 8.2.3

実装

UpsertController.php
use Illuminate\Support\Facades\Log;
use App\Models\Setting;
use Exception;

// ... 略

/**
* アップサートする
* 
* @param  設定情報
* @return エラー有無情報
*/
public function regist($param)
{
    Log::debug(__FUNCTION__);

    // 初期設定
    $is_error    = false;

    // トランザクション開始
    DB::beginTransaction();

    try {

        // 検索情報
        $searchStr = [
            'column_a'  => $params['column_a'] // 検索したいカラム
        ];

        // アップサート情報
        $upsertStr = [
            'column_1' => $params['column_1'],
            'column_2' => $params['column_2'],
            // ... 略
        ];

        // アップサートする
        $result = Setting::updateOrCreate($search_data, $upsert_data);
        if ($result == false) {
            throw new Exception('アップサート中にエラーが発生しました。');
        }

    } catch (Exception $e) {
        Log::error(get_class($this).':'.__FUNCTION__);
        Log::error($e->getMessage());
        $is_error = true;
    
    } finally {
        // エラーが存在する場合
        if ($is_error == false) {
            DB::commit();
        // エラーが存在しない場合
        } else {
            DB::rollback();
        }
    }

    // エラー有無情報を返す
    return $is_error;
}

最後に

最後まで閲覧いただきありがとうございました。
ご意見、ご指摘ありましたら、コメントお願いいたします。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?