欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

PHP Laravel軟刪除的實現(xiàn)方法介紹

 更新時間:2022年09月02日 14:44:51   作者:PeakXin  
軟刪除就是邏輯刪除,數(shù)據(jù)保留單標(biāo)記上刪除狀態(tài),一般我們會用刪除時間來作為標(biāo)記,這樣標(biāo)記狀態(tài)有了,刪除時間也有了

用Laravel 自帶的 Eloquent ORM 來實現(xiàn)軟刪除。

首先在數(shù)據(jù)遷移文件中添加刪除時間字段

./database/migrations/2014_10_12_000000_create_users_table.php

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
            $table->softDeletes()->comment('刪除時間');// 默認(rèn)添加 deleted_at 字段
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
};

執(zhí)行 php artisan migrate 運行遷移文件

修改對應(yīng)的數(shù)據(jù)模型

./app/Models/User.php

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
    use SoftDeletes;// 開啟軟刪除
    protected $guarded = [];// 不可以注入的字段數(shù)據(jù),使用create方法才有效
}

軟刪除方法

直接調(diào)用delete()方法或者destroy()方法即可

User::destroy($id);

這時候查詢的數(shù)據(jù)自動添加過濾條件 deleted_at = NULL

恢復(fù)刪除

User::onlyTrashed()->where('id', $id)->restore();

永久刪除

直接刪除數(shù)據(jù)

User::forceDeleted($id);

查詢包含已刪除的數(shù)據(jù)

使用 withTrashed()可以查詢出包含已刪除的數(shù)據(jù)

User::withTrashed()->get();

只查詢已刪除的數(shù)據(jù)

使用 onlyTrashed()可以只查詢出已刪除的數(shù)據(jù)

User::onlyTrashed()->get();

到此這篇關(guān)于PHP Laravel軟刪除的實現(xiàn)方法介紹的文章就介紹到這了,更多相關(guān)PHP Laravel軟刪除內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論