操作Users模型实现物理删除与软删除;

Original 2019-04-21 16:09:41 170
abstract:<?php namespace app\index\controller; use think\Controller; use think\Db; use app\index\model\Users as UsersModel; class Users extends Controller { //
<?php
namespace app\index\controller;

use think\Controller;
use think\Db;
use app\index\model\Users as UsersModel;

class Users extends Controller
{
// 使用模型删除  destroy();
public function del()
{
    // 使用闭包删除
    UsersModel::destroy(function($query){
        $query->where('weight','>',130);// 体重大于130的删除
    });
}


/**
 * 实现软删除的步骤:
 *  1、在数据库表中(users) 添加字段:delete_time;
 *  2、在Users模型中引入SoftDelete类库;think\model\concern\SoftDelete;
 *  3、在Users模型中添加两个属性
 *     $deleteTime = 'delete_time';// 与数据表字段名一致
 *     $defaultSoftDelete = 0;// 添加删除标志默认值;
 *  4、在控制器中使用withTrashed() 方法实现软删除
 *  5、查看已删除的软删除;onlyTrashed();
 *  6、恢复软删除 (new UsersModel)->restore(条件);
 */

// 使用模型实现软删除
public function softdelete()
{
    // 如果想在查询的时候看到已经被删除的记录  使用:withTrashed();
    $res = UsersModel::withTrashed()->where('uid','<',5)->select();
    dump($res);
}


// 恢复软删除 使用依赖注入方式恢复
public function restore(UsersModel $users)
{
    // 恢复软删除
    $res = $users->restore(['uid'=>1]);
    dump($res);
}
}

?>


Correcting teacher:天蓬老师Correction time:2019-04-22 10:19:30
Teacher's summary:如果你是软删除, 那么在查询的时候, 一定要注意一下查询条件... 是否允许过滤掉已软删除的记录, ....

Release Notes

Popular Entries