#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 = 'posts'; //设置主键 public $primaryKey = 'id'; //设置日期时间格式 public $dateFormat = 'U'; protected $guarded = ['id','views','user_id','updated_at','created_at']; protected $dates = ['delete_at']; }
然後對應的資料庫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('posts', function (Blueprint $table) { $table->softDeletes(); }); } ...//其它方法 }
然後運行:
php artisan migrate
這樣posts中就有了deleted_at列。接下來,我們在控制器中寫測試程式碼:
$post = Post::find(6); $post->delete(); if($post->trashed()){ echo '软删除成功!'; dd($post); }else{ echo '软删除失败!'; }
那如果想要在查詢結果中包含軟刪除的記錄呢?可以使用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('id','>',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中文網其他相關文章!

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

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

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

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

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

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

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

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


熱AI工具

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

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

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

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

熱門文章

熱工具

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

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

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

SublimeText3 Linux新版
SublimeText3 Linux最新版

EditPlus 中文破解版
體積小,語法高亮,不支援程式碼提示功能