模型时间戳+软删除

开启自动时间戳的话, 需要在 database.php 下开启配置

// 自动写入时间戳字段
'auto_timestamp'  => true,

默认的字段名为

增加时间 create_time

更新时间 update_time

开启之后, 我们新增一条数据的话, 就会自动给我们加上时间戳, 但问题也来了. 有的表没有这2个字段, 所以,不建议开启全局的配置.

我们将 'auto_timestamp' 修改为 false. 

关闭之后, 我们来到我们需要开启自动时间戳的模型类, 加上如下 

protected $autoWriteTimestamp = true;
class User extends Model
{
    protected $autoWriteTimestamp = true;
    
    public function setPasswordAttr($val)
    {
        return md5($val);
    }

}

1. 现在有一个问题, 如果我们的数据库的 添加时间和更新时间的字段 不是默认的, 那该如何操作呢?  

例如我们现在的2个字段是 create_at, update_at, 我们需要在 模型类中, 声明这2个变量, 让系统知道.

//重新声明2个字段名
protected $createTime = 'create_at';
protected $updateTime = 'update_at';

2. 如果现在我们只需要更新时间, 不需要创建时间, 我们只需要关闭即可. 如下

//重新声明2个字段名
protected $createTime = false;
protected $updateTime = 'update_at';

数据软删除

想实现数据软删除的话, 我们需要在表中加入一个字段 delete_time(默认), int类型, 为null, 且默认值就是NULL, 无符号.

意义是: 如果为null, 表明这条数据没有被删除, 如果不为null, 则表示这条数据在 该时间戳 被删除.

1. 使用的话, 现在model类中, 引入 

use traits\model\SoftDelete;

2. 在类中 声明下

class User extends Model
{
    use SoftDelete;
}

3. 此时在 控制器中, 删除主键为1的记录.

$res = User::destroy(1);

此时, 我们获取下 主键为1 的这条记录,如下, 返回 null, 查找不到这条数据.

$res = User::get(1);
dump($res);

4. 如果想获取到 主键为1的这条数据, 用如下方法

$res = User::withTrashed(true)->find(1);
//获取原始数据
dump($res->getData());

5. 如何获取所有被软删除的数据, 如下

//获取所有软删除的数据
$res = User::onlyTrashed()->select();

foreach ($res as $val) {
    dump($val->getData());
}

6. 如何修改 delete_time 这个默认字段, 例如我们表中的是 delete_at , 代码如下, 需要在model中声明一下 deleteTime

class User extends Model
{
    use SoftDelete;

    protected $deleteTime = 'delete_at';
}

7. 如上, 我们在 User模型中,定义了 软删除, 那如何真正的删除某个数据呢? 在后面加上一个true值.

$res = User::destroy(3, true);

delete方法如下, 也是在 delete 中加入true.

$user = User::get(4);
$res  = $user->delete(true);
发布了88 篇原创文章 · 获赞 6 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/codipy/article/details/92833081
今日推荐