Blogger Information
Blog 22
fans 0
comment 0
visits 21737
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
作业:1.实例演示闭包实现查询 2.实例实现软删除功能并详细写出软删除的步骤
岑勋的博客
Original
946 people have browsed it

//模型类 model\Staff.php

<?php
namespace app\index\model;
use think\Model;
use think\Model\concern\SoftDelete;  //trait方法集
class Staff extends Model
{
   use SoftDelete;
   protected $table = 'staff';
   protected $pk = 'staff_id';
   //设置删除时间的字段名
   protected $delete_time = 'delete_time';
   //设置软删除字段的默认值
//    protected $defaultSoftdelete = 0;
}

//控制类 controller\Staff.php

<?php
namespace app\index\controller;
use think\Controller;
use app\index\model\Staff as StaffModel;
use think\Db;

class Staff extends Controller
{
   //模型查询 get(主键/闭包)  all(主键/闭包)
   public function query()
   {
       $res = StaffModel::all(function ($query){
           $query->where('staff_id','<',10)->where('sex',1);
       });
       dump($res);
   }

   public function softDelete()
   {
       /*步骤:
        * 1、在表中增加字段:delete_time(作为删除标志):protected $delete_time = 'delete_time';
        * 2、模型类文件需引入软删除的trait类:  use think\model\concern\SoftDelete
        * 3、在模型类内还需 use SoftDelete;
        */
       //当数据表中没有delete_time字段,则先添加
       $sql = "ALTER TABLE `staff` ADD delete_time INT NOT NULL DEFAULT 0"; //增加字段
       $sql2 = "select * from `staff` where delete_time is null";  //判断某字段是否空
       if (Db::table('staff')->query($sql2)) {
            Db::table('staff')->execute($sql);
       }
       $res = StaffModel::destroy(2);  // UPDATE `staff` SET `delete_time` = 1527235261 WHERE `staff_id` = 2
       return $res? '成功删除': '删除失败';
    }
}

Correction status:qualified

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post