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 3 years have passed since last update.

【Laravel】外部制約キーを設定しているデータを論理削除してみた

Posted at

はじめに

外部制約キーを設定しているデータは、通常テーブルから削除する事ができない。
ただ、DBのテーブルからデータを削除には__論理削除__と__物理削除__の2種類ある。
先ほど挙げた通常の削除とは__物理削除__の事を指します。
では、__物理削除__の場合はどうなるのか、検証していくぅ!

マイグレーション作成

外部制約キーを使用するために、まずテーブルを2つ用意しましょう。
親テーブルには論理削除の為に、__deleted_at__カラムを用意しましょう。

CreateSchoolsTable
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('schools', function (Blueprint $table) {
            $table->id();
            $table->timestamps();
            $table->softDeletes('deleted_at', 0);
        });
    }

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

子テーブルには__ForeignKey__を指定しましょう。

CreateStudentsTable
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('students', function (Blueprint $table) {
            $table->id();
            $table->foreignId('school_id')->constrained();
            $table->timestamps();
        });
    }

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

はいこれでおけい。

Model作成

はい次ぃー、Modelの作成をしていきましょう。
親テーブルのモデルは論理削除を行いたいので、__SoftDelete__を使用します。

School
use Illuminate\Database\Eloquent\SoftDeletes;

class School extends Model
{
    use SoftDeletes;
}

次に子テーブルのモデルのカラムは親のテーブルのIDだけですので、これだけ。

Student
class Student extends Model
{
    protected $fillable = [
        'school_id'
    ];
}

削除してみる

まずは、外部制約キーが動いているか確認する為に物理削除してみる。
まずはSchoolモデルの__SoftDelete__をコメントアウトして、削除してみた。
スクリーンショット 2020-06-03 23.53.27.png
英語で何て書いてあるかよく分かりませんが、外部制約キーの関係で削除できませんと書いてあるのでしょう。

次にSchoolモデルの__SoftDelete__をコメントアウトを解錠して論理削除して見ましょう。

School
{
    "id":1,
    "created_at":null,
    "updated_at":"2020-06-03T14:59:17.000000Z",
    "deleted_at":"2020-06-03T14:59:17.000000Z"
}

__deleted_at__に論理削除された時刻が挿入されています、論理削除成功ですね。
ちなみに、Schoolのidが1のデータはDB上には残っていますが、取得をしようとするとnullで返ってきます。
しっかりしていますね。

結果

DBからデータが無くなっている訳ではないんだから論理削除できて当たり前だよね。
また気になることがあれば検証していきますぅ!
ではまた。

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?