PHP Laravel軟刪除的實現(xiàn)方法介紹
用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)文章
php中將一段數(shù)據(jù)存到一個txt文件中并顯示其內(nèi)容
這篇文章主要介紹了php中將一段數(shù)據(jù)存到一個txt文件中,并獲取其內(nèi)容顯示的實現(xiàn)代碼,需要的朋友可以參考下2014-08-08php時區(qū)轉(zhuǎn)換轉(zhuǎn)換函數(shù)
godaddy主機在國外。把站點建站國外,顯示時間時可能需要時區(qū)轉(zhuǎn)換,下面是個方便的工具函數(shù),用于時區(qū)轉(zhuǎn)換2014-01-01php輸出控制函數(shù)和輸出函數(shù)生成靜態(tài)頁面
這篇文章主要為大家詳細(xì)介紹了php輸出控制函數(shù)和輸出函數(shù)生成靜態(tài)頁面,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-06-06php magic_quotes_gpc的一點認(rèn)識與分析
最近一直在做一個文章發(fā)布系統(tǒng),做了改,改了做,一直到現(xiàn)在還沒竣工.... 為了達到更好的兼容性,其中的程序涉及到了magic_quotes_gpc,看了下手冊,又找了些資料,分析了下,分享給大家。2008-08-08header函數(shù)設(shè)置響應(yīng)頭解決php跨域問題實例詳解
在本篇文章里小編給大家整理的是關(guān)于header函數(shù)設(shè)置響應(yīng)頭解決php跨域問題實例內(nèi)容,有需要的朋友們可以參考下。2020-01-01