PHP Laravel軟刪除的實現方法介紹
用Laravel 自帶的 Eloquent ORM 來實現軟刪除。
首先在數據遷移文件中添加刪除時間字段
./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('刪除時間');// 默認添加 deleted_at 字段
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('users');
}
};執(zhí)行 php artisan migrate 運行遷移文件
修改對應的數據模型
./app/Models/User.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
use SoftDeletes;// 開啟軟刪除
protected $guarded = [];// 不可以注入的字段數據,使用create方法才有效
}軟刪除方法
直接調用delete()方法或者destroy()方法即可
User::destroy($id);
這時候查詢的數據自動添加過濾條件 deleted_at = NULL
恢復刪除
User::onlyTrashed()->where('id', $id)->restore();永久刪除
直接刪除數據
User::forceDeleted($id);
查詢包含已刪除的數據
使用 withTrashed()可以查詢出包含已刪除的數據
User::withTrashed()->get();
只查詢已刪除的數據
使用 onlyTrashed()可以只查詢出已刪除的數據
User::onlyTrashed()->get();
到此這篇關于PHP Laravel軟刪除的實現方法介紹的文章就介紹到這了,更多相關PHP Laravel軟刪除內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

