若是须要确认模型是否存在某个记录,可使用 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