PHP Laravel軟刪除的實(shí)現(xiàn)方法介紹
用Laravel 自帶的 Eloquent ORM 來(lái)實(shí)現(xiàn)軟刪除。
首先在數(shù)據(jù)遷移文件中添加刪除時(shí)間字段
./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('刪除時(shí)間');// 默認(rèn)添加 deleted_at 字段 }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('users'); } };
執(zhí)行 php artisan migrate
運(yùn)行遷移文件
修改對(duì)應(yīng)的數(shù)據(jù)模型
./app/Models/User.php
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class User extends Model { use SoftDeletes;// 開(kāi)啟軟刪除 protected $guarded = [];// 不可以注入的字段數(shù)據(jù),使用create方法才有效 }
軟刪除方法
直接調(diào)用delete()
方法或者destroy()
方法即可
User::destroy($id);
這時(shí)候查詢的數(shù)據(jù)自動(dòng)添加過(guò)濾條件 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軟刪除的實(shí)現(xiàn)方法介紹的文章就介紹到這了,更多相關(guān)PHP Laravel軟刪除內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
php中將一段數(shù)據(jù)存到一個(gè)txt文件中并顯示其內(nèi)容
這篇文章主要介紹了php中將一段數(shù)據(jù)存到一個(gè)txt文件中,并獲取其內(nèi)容顯示的實(shí)現(xiàn)代碼,需要的朋友可以參考下2014-08-08php時(shí)區(qū)轉(zhuǎn)換轉(zhuǎn)換函數(shù)
godaddy主機(jī)在國(guó)外。把站點(diǎn)建站國(guó)外,顯示時(shí)間時(shí)可能需要時(shí)區(qū)轉(zhuǎn)換,下面是個(gè)方便的工具函數(shù),用于時(shí)區(qū)轉(zhuǎn)換2014-01-01php輸出控制函數(shù)和輸出函數(shù)生成靜態(tài)頁(yè)面
這篇文章主要為大家詳細(xì)介紹了php輸出控制函數(shù)和輸出函數(shù)生成靜態(tài)頁(yè)面,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-06-06php magic_quotes_gpc的一點(diǎn)認(rèn)識(shí)與分析
最近一直在做一個(gè)文章發(fā)布系統(tǒng),做了改,改了做,一直到現(xiàn)在還沒(méi)竣工.... 為了達(dá)到更好的兼容性,其中的程序涉及到了magic_quotes_gpc,看了下手冊(cè),又找了些資料,分析了下,分享給大家。2008-08-08header函數(shù)設(shè)置響應(yīng)頭解決php跨域問(wèn)題實(shí)例詳解
在本篇文章里小編給大家整理的是關(guān)于header函數(shù)設(shè)置響應(yīng)頭解決php跨域問(wèn)題實(shí)例內(nèi)容,有需要的朋友們可以參考下。2020-01-01