搜尋
首頁php框架Laravel一文了解laravel模型刪除和軟刪除

一文了解laravel模型刪除和軟刪除

#1、刪除模型

#1.1 使用delete刪除模型

刪除模型很簡單,先取得要刪除的模型實例,然後呼叫delete方法即可:

$post = Post::find(5);
if($post->delete()){
    echo '删除文章成功!';
}else{
    echo '删除文章失败!';
}

該方法傳回true或false。

1.2 使用destroy刪除模型

當然如果已知要刪除的模型id的話,可以用更簡單的方法destroy直接刪除:

$deleted = Post::destroy(5);

你也可以一次傳入多個模型id刪除多個模型:

$deleted = Post::destroy([1,2,3,4,5]);

呼叫destroy方法傳回被刪除的記錄數。

1.3 使用查詢建構器刪除模型

既然前面提到Eloquent模型本身就是查詢建構器,也可以使用查詢建構器風格刪除模型,例如我們要刪除所有瀏覽數為0的文章,可以使用以下方式:

$deleted = Models\Post::where('views', 0)->delete();

傳回結果為被刪除的文章數。

2、軟刪除實作

上述刪除方法都會將資料表記錄從資料庫刪除,此外Eloquent模型也支援軟體刪除。

所謂軟刪除指的是資料表記錄並未真的從資料庫刪除,而是將表記錄的標識狀態標記為軟刪除,這樣在查詢的時候就可以加以過濾,讓對應表記錄看上去是被」刪除「了。 Laravel中使用了一個日期欄位作為識別狀態,這個日期欄位可以自定義,這裡我們使用deleted_at,如果對應模型被軟刪除,則deleted_at欄位的值為刪除時間,否則該值為空。

要讓Eloquent模型支援軟刪除,還要做一些設定。首先在模型類別中要使用SoftDeletestrait,該trait為軟體刪除提供一系列相關方法,具體可參考原始碼Illuminate\Database\Eloquent\SoftDeletes,此外還要設定$date屬性數組,將deleted_at置於其中:

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Post extends Model
{
    use SoftDeletes;
    //设置表名
    public $table = &#39;posts&#39;;
    //设置主键
    public $primaryKey = &#39;id&#39;;
    //设置日期时间格式
    public $dateFormat = &#39;U&#39;;
    protected $guarded = [&#39;id&#39;,&#39;views&#39;,&#39;user_id&#39;,&#39;updated_at&#39;,&#39;created_at&#39;];
    protected $dates = [&#39;delete_at&#39;];
}

然後對應的資料庫posts中加入deleted_at列,我們使用遷移來實現,先執行Artisan指令:

php artisan make:migration alter_posts_deleted_at --table=posts

然後編輯產生的PHP檔案如下:

<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AlterPostsDeletedAt extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table(&#39;posts&#39;, function (Blueprint $table) {
            $table->softDeletes();
        });
    }
    ...//其它方法
}

然後運行:

php artisan migrate

這樣posts中就有了deleted_at列。接下來,我們在控制器中寫測試程式碼:

$post = Post::find(6);
$post->delete();
if($post->trashed()){
    echo &#39;软删除成功!&#39;;
    dd($post);
}else{
    echo &#39;软删除失败!&#39;;
}

那如果想要在查詢結果中包含軟刪除的記錄呢?可以使用SoftDeletes trait上的withTrashed方法:

$posts = Post::withTrashed()->get();
dd($posts);

有時候我們只想要查看被軟體刪除的模型,這也有招,透過SoftDeletes上的onlyTrashed方法即可:

$posts = Post::onlyTrashed()->get();
dd($posts);

軟體刪除復原

有時候我們需要還原被軟體刪除的模型,可以使用SoftDeletes提供的restore方法:

還原單個模型

$post = Post::find(6);
$post->restore();

有點問題,ID為6的已經被軟刪除了,Post::find(6) 是查不到資料的,

應該

$post = Post::withTrashed()->find(6);
$post->restore();

恢復多個模型

Post::withTrashed()->where(&#39;id&#39;,&#39;>&#39;,1)->restore();

恢復所有模型

Post::withTrashed()->restore();

#恢復關聯查詢模型

$post = Post::find(6);
$post->history()->restore();

強制刪除

如果模型配置了軟體刪除但我們確實要刪除改模型對應資料庫表記錄,則可以使用SoftDeletes提供的forceDelete方法:

$post = Post::find(6);
$post->forceDelete();

PHP中文網,大量的免費laravel入門教學,歡迎線上學習!

本文轉自:https://blog.csdn.net/weixin_38112233/article/details/78574007

以上是一文了解laravel模型刪除和軟刪除的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文轉載於:CSDN。如有侵權,請聯絡admin@php.cn刪除
包容的幻想:解決偏遠工作中的孤立和孤獨感包容的幻想:解決偏遠工作中的孤立和孤獨感Apr 25, 2025 am 12:28 AM

Tocombatisolationandlonelinessinremotework,companiesshouldimplementregular,meaningfulinteractions,provideequalgrowthopportunities,andusetechnologyeffectively.1)Fostergenuineconnectionsthroughvirtualcoffeebreaksandpersonalsharing.2)Ensureremoteworkers

Laravel用於全堆棧開發:綜合指南Laravel用於全堆棧開發:綜合指南Apr 25, 2025 am 12:27 AM

laravelispularfullull-stackDevelopmentBecapeitOffersAsAseAseAseAseBlendOfbackendEdpoperandPowerandForterFlexibility.1)ITSbackEndCapaPabilities,sightifyDatabaseInteractions.2)thebladeTemplatingEngingEngineAllolowsLows

視頻會議攤牌:為遠程會議選擇正確的平台視頻會議攤牌:為遠程會議選擇正確的平台Apr 25, 2025 am 12:26 AM

選擇視頻會議平台的關鍵因素包括用戶界面、安全性和功能。 1)用戶界面應直觀,如Zoom。 2)安全性需重視,MicrosoftTeams提供端到端加密。 3)功能需匹配需求,GoogleMeet適合簡短會議,CiscoWebex提供高級協作工具。

哪些數據庫版本與最新的Laravel兼容?哪些數據庫版本與最新的Laravel兼容?Apr 25, 2025 am 12:25 AM

最新版本的Laravel10與MySQL5.7及以上、PostgreSQL9.6及以上、SQLite3.8.8及以上、SQLServer2017及以上兼容。這些版本選擇是因為它們支持Laravel的ORM功能,如MySQL5.7的JSON數據類型,提升了查詢和存儲效率。

將Laravel用作全棧框架的好處將Laravel用作全棧框架的好處Apr 25, 2025 am 12:24 AM

Laravelisanexcellentchoiceforfull-stackdevelopmentduetoitsrobustfeaturesandeaseofuse.1)ItsimplifiescomplextaskswithitsmodernPHPsyntaxandtoolslikeBladeforfront-endandEloquentORMforback-end.2)Laravel'secosystem,includingLaravelMixandArtisan,enhancespro

Laravel的最新版本是什麼?Laravel的最新版本是什麼?Apr 24, 2025 pm 05:17 PM

Laravel10,releasedonFebruary7,2023,isthelatestversion.Itfeatures:1)Improvederrorhandlingwithanewreportmethodintheexceptionhandler,2)EnhancedsupportforPHP8.1featureslikeenums,and3)AnewLaravel\Promptspackageforinteractivecommand-lineprompts.

最新的Laravel版本如何簡化開發?最新的Laravel版本如何簡化開發?Apr 24, 2025 pm 05:01 PM

thelatestlaravelververversionenhancesdevelopmentwith:1)簡化的inimpliticmodelbinding,2)增強EnhancedeloquentcapabibilitionswithNewqueryMethods和3)改善了supportorfortormodernphpfortornphpforternphpfeatureserslikenamedargenamedArgonedArgonsemandArgoctess,makecodingMoreftermeforefterMealiteFficeAndEnjoyaigaigaigaigaigaiganigaborabilyaboipaigyAndenjoyaigobyabory。

在哪裡可以找到最新的Laravel版本的發行說明?在哪裡可以找到最新的Laravel版本的發行說明?Apr 24, 2025 pm 04:53 PM

你可以在laravel.com/docs找到最新Laravel版本的發布說明。 1)發布說明提供了新功能、錯誤修復和改進的詳細信息。 2)它們包含示例和解釋,幫助理解新功能的應用。 3)注意新功能的潛在復雜性和向後兼容性問題。 4)定期審查發布說明可以保持更新並激發創新。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能