LoginSignup
0
0

More than 3 years have passed since last update.

Laravelの多対多で中間テーブルのレコードを論理削除する

Last updated at Posted at 2021-05-04

Laravelの多対多のリレーションで、中間テーブルに論理削除を実装する。

テーブル準備

マイグレーションファイル作成

 php artisan make:migration create_article_tag_table

deleted_atカラムを追加する

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateArticleTagTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('article_tag', function (Blueprint $table) {
            $table->integer('article_id');
            $table->integer('tag_id');
            $table->timestamp('deleted_at')->nullable();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('article_tag');
    }
}

中間テーブルの更新

updateExistingPivotを使用して中間テーブルを更新。

use Carbon\Carbon;

public function delete(Request $request, Article $article)
{
    $ids = $article->tags->pluck('id');
    $article->tags()->updateExistingPivot($ids, ['deleted_at' => Carbon::now()]);

    return redirect('/articles');
}

論理削除以外のレコードを取得

whereNullメソッドでdeleted_atを使用すると、論理削除以外のレコードが取得できます。

use App\Models\Tag;

class Article extends Model
{
    public function tags()
    {
        return $this
                ->belongsToMany(Tag::class)
                ->whereNull('deleted_at')
                ->withTimestamps();
    }
}

中間テーブルで論理削除するべきか

中間テーブルで論理削除をするのなら、そもそもテーブル設計を見直す必要がありそうです。

注意: ピボットモデルでは、SoftDeletesトレイトを使わないほうが良いでしょう。ピボットレコードのソフト削除が必要な場合は、ピボットモデルを実際のEloquentモデルに変換することを考えてください。

「とりあえず削除フラグ」はSQLアンチパターンです。

参考
https://www.it-swarm-ja.com/ja/laravel/%E5%A4%9A%E5%AF%BE%E5%A4%9A%E3%81%AE%E9%96%A2%E4%BF%82%E3%81%AE%E3%81%9F%E3%82%81%E3%81%AE%E4%B8%AD%E9%96%93%E3%83%86%E3%83%BC%E3%83%96%E3%83%AB%E3%81%AE%E3%82%BD%E3%83%95%E3%83%88%E5%89%8A%E9%99%A4/1072983220/

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