若是須要確認模型是否存在某個記錄,可使用 exists() 方法。不一樣於 find() 方法返回模型對象,exists() 返回 boolean 類型已肯定是否存在模型對象。php
<?php // Determine if the user exists User::where('email', 'test@gmail.com')->exists();
經過 SoftDeletes 能夠判斷給定的模型是否棄用。使用 trashed() 方法經過判斷模型的 created_at 字段是否爲 null 來肯定模型是否軟刪除laravel
<?php // Determine if the model is trashed $post->trashed();
當咱們對已使用 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();
使用 restore() 方法將 created_at 字段設爲 null 實現恢復軟刪除的模型對象。less
<?php // Restore the model $food->restore();
某些場景下咱們須要複製一個現有模型,經過 replicate() 方法能夠複製已有模型所有屬性。post
<?php // Deep copy the model $new = $model->replicate();
提示: 若是須要同時複製模型的關係模型,則須要手動的迭代建立,replicate() 是沒法實現該功能的。學習
Eloquent ORM 有不少很讚的特性,但有些因爲不經常使用而不爲人知。經過對 Laravel 文檔,論壇和 Laravel 源碼的深刻學習和研究。
咱們能夠發現不少實用的 Laravel 特性。rest