您现在的位置是:首页 > 经验记录>Laravel日记>Laravel软删除操作以及回收站功能实现 网站首页 Laravel日记
Laravel软删除操作以及回收站功能实现
数据库数据删除Laravel有自带的软删除功能,挺好用的。
一、在模型中需要使用SoftDeletestrait
,该trait
为软删除提供一系列相关方法,具体可参考源码Illuminate\Database\Eloquent\SoftDeletes
,此外还要设置$date
属性数组,将deleted_at
置于其中,下面为Model实例:
<? phpnamespace App\Model\Backend; use App\Http\Response; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; use Request; class User extends Model{ use SoftDeletes; protected $table = 'users'; //表名 protected $primaryKey = 'id'; //主键 protected $datas = ['deleted_at'];
2、向数据库中的相应数据表添加 delete_at
字段, 执行下面命令生成迁移文件
php artisan make:migration add_deleted_at_to_users_table --table=users php artisan migrate //执行迁移文件
注:你也可以选择手动添加该字段如下↓(默认选择为null)
3、在Model
文件里面执次下面操作即可
delete(); //删除用户 //withTrashed() 查询时检索所有数据 //onlyTrashed() 查询时只检索已删除数据 //查询正常数据操作就不写了,正常查询出来的就都是未删除数据 //restore()还原数据,就是清空deleted_at为null } 实例语句: $user = User::withTrashed()->where('id', $id)->git();//查询包括已删除的所有数据
原文参考994914376的文章
随机推荐
文章评论
未开放