鮮為人知的 Laravel Eloquent 模型方法
1 判斷模型是否有記錄
如果需要確認模型是否存在某個記錄,可以使用 exists() 方法。不同於 find() 方法返回模型對象,exists() 返回 boolean 類型已確定是否存在模型對象。
<?php
// Determine if the user exists
User::where('email', 'test@gmail.com')->exists();
2 判斷模型是否被軟刪除
通過 SoftDeletes 可以判斷給定的模型是否棄用。使用 trashed() 方法通過判斷模型的 created_at 字段是否為 null 來確定模型是否軟刪除
<?php
// Determine if the model is trashed
$post->trashed();
3 刪除棄用模型
當我們對已使用 SoftDeletes 進行軟刪除的模型對象調用 delete() 方法刪除對象時,並非真的刪除該模型對象在數據庫中的記錄,
而僅僅是設置 created_at 字段的值。那如何真的刪除一個已軟刪除的模型對象呢?在這種情況時我們需要使用 forceDelete() 方法實現從數據庫中刪除記錄。
<?php
// Delete the model permanently
$product->forceDelete();
// A little trick, do determine when to soft- and force delete a model
$product->trashed() ? $product->forceDelete() : $product->delete();
4 恢復軟刪除的模型
使用 restore() 方法將 created_at 字段設為 null 實現恢復軟刪除的模型對象。
<?php
// Restore the model
$food->restore();
5 複製模型對象
某些場景下我們需要複製一個現有模型,通過 replicate() 方法可以複製已有模型全部屬性。
<?php
// Deep copy the model
$new = $model->replicate();
提示: 如果需要同時複製模型的關係模型,則需要手動的迭代創建,replicate() 是無法實現該功能的。
總結
Eloquent ORM 有很多很讚的特性,但有些由於不常用而鮮為人知。通過對 Laravel 文檔,論壇和 Laravel 源碼的深入學習和研究。
我們可以發現很多實用的 Laravel 特性。
Less Known Eloquent Model Actions