Laravel 软删除操作

数据库数据删除有些数据肯定不是真的从数据库里面直接删除,这时候就会用到假删除。

1、首先在模型中要使用SoftDeletestrait,该trait为软删除提供一系列相关方法,具体可参考源码Illuminate\Database\Eloquent\SoftDeletes ,此外还要设置$date属性数组,将deleted_at置于其中:

<?php

namespace 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 //执行迁移文件

3、在Model文件里面执次下面操作即可

<?php
namespace 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'];

        public static function delete() 
        {
            self::whereIn('id', $ids)->delete(); //删除用户
            withTrashed() 显示所有数据
            onlyTrashed() 显示删除数所
            restore()还原数据
        }
本作品采用《CC 协议》,转载必须注明作者和本文链接
994914376
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
讨论数量: 6

请问这里的delete() 方法具体操作是什么,还是不太清楚,能杰斯下吗,谢谢

5年前 评论
994914376

@life-is-learning 因为上面引入了SoftDeletes 所以你 delete 的时候你的数据只是不会显示,但还是在数据表中。

5年前 评论

如果在关联中呢?比如:hasMany 如何使用 withTrashed() 显示所有数据 onlyTrashed() 显示删除数所 restore()还原数据

5年前 评论

datas 改成dates

5年前 评论

protected $dates = ['deleted_at']; 这个是干啥用的

2年前 评论

写的不明不白的,$ids都不知道哪来的

2年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!