Laravel5.1 框架模型軟刪除操作例項分析
阿新 • • 發佈:2020-01-09
本文例項講述了Laravel5.1 框架模型軟刪除操作。分享給大家供大家參考,具體如下:
軟刪除是比較實用的一種刪除手段,比如說 你有一本賬 有一筆記錄你覺得不對給刪了 過了幾天發現不應該刪除,這時候軟刪除的目的就實現了 你可以找到已經被刪除的資料進行操作 可以是還原也可以是真正的刪除。
1 普通刪除
在軟刪除之前咱先看看普通的刪除方法:
1.1 直接通過主鍵刪除
public function getDelete() { Article::destroy(1); Article::destroy([1,2,3]); }
1.2 獲取model後刪除
public function getDelete() { $article = Article::find(3); $article->delete(); }
1.3 批量刪除
public function getDelete() { // 返回一個整形 刪除了幾條資料 $deleteRows = Article::where('id','>',3)->delete(); dd($deleteRows); // 2 }
2 軟刪除
2.1 準備工作
如果你要實現軟刪除 你應該提前做3件事情:
- 新增deleted_at 到模型的 $date 屬性中。
- 在模型中使用 Illuminate\Database\Eloquent\SoftDeletes 這個trait
- 保證你的資料表中有deleted_at列 如果沒有就新增這個列。
首先我們做第一步和第二步:
<?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class Article extends Model { // 使用SoftDeletes這個trait use SoftDeletes; // 白名單 protected $fillable = ['title','body']; // dates protected $dates = ['deleted_at']; }
然後我們生成一個遷移檔案來增加deleted_at列到資料表:
class InsertDeleteAtIntroArticles extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('articles',function (Blueprint $table) { $table->softDeletes(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('articles',function (Blueprint $table) { $table->dropSoftDeletes(); }); } }
2.2 實現軟刪除
現在我們就可以刪除一條資料試試啦:
public function getDelete() { $article = Article::first(); $article->delete(); }
↑ 當我們刪了這條資料後 在資料表中的表示是 deleted_at 不為空 它是一個時間值,當delete_at不為空時 證明這條資料已經被軟刪除了。
2.3 判斷資料是否被軟刪除
if ($article->trashed()){ echo '這個模型已經被軟刪除了'; }
2.4 查詢到被軟刪除的資料
有一點需要注意,當資料被軟刪除後 它會自動從查詢資料中排除、就是它無法被一般的查詢語句查詢到。當我們想要查詢軟刪除資料時 可以使用withTrashed方法
public function getIndex() { $article = Article::withTrashed()->first(); if ($article->trashed()){ echo '被軟刪除了'; // 程式碼會執行到這一行 } }
我們還可以使用onlyTrashed,它和withTrashed的區別是 它只獲得軟刪除的資料。
public function getIndex() { $articles = Article::onlyTrashed()->where('id','<','10')->get()->toArray(); dd($articles); }
2.5 恢復被軟刪除的資料
public function getIndex() { $article = Article::withTrashed()->find(6); $article->restore(); }
2.6 永久刪除資料
public function getIndex() { $article = Article::withTrashed()->find(6); $article->forceDelete(); }
更多關於Laravel相關內容感興趣的讀者可檢視本站專題:《Laravel框架入門與進階教程》、《php優秀開發框架總結》、《php面向物件程式設計入門教程》、《php+mysql資料庫操作入門教程》及《php常見資料庫操作技巧彙總》
希望本文所述對大家基於Laravel框架的PHP程式設計有所幫助。