6-13ThinkPHP5模型的删除操作:delete()和destroy()方法

6-13ThinkPHP5模型的删除操作:delete()和destroy()方法

窝平佃伪磋郡狈疚九棵孔琳巷

6-13ThinkPHP5模型的删除操作:delete()和destroy()方法第1张

数据表结构

6-13ThinkPHP5模型的删除操作:delete()和destroy()方法第2张

删除id=20的吴三桂2号

1.查询出吴三桂2号

<?php
namespace app\index\controller;
use app\index\model\Staff;
class Index
{
    public function index()
    {
        $result=Staff::get(['id'=>['>',19]]);
        dump($result->getData());
    }
}

执行:

6-13ThinkPHP5模型的删除操作:delete()和destroy()方法第3张

删除吴三桂2号

<?php
namespace app\index\controller;
use app\index\model\Staff;
class Index
{
    public function index()
    {
        $result=Staff::get(['id'=>['>',19]]);
        $affected=$result->delete();
        dump($affected);
    }
}

执行:

6-13ThinkPHP5模型的删除操作:delete()和destroy()方法第4张

此时,吴三桂被删除

6-13ThinkPHP5模型的删除操作:delete()和destroy()方法第5张

注意delete()只能删除一条记录,且delete()方法不允许有参数


destory()删除1条或者多条数据

查询如下数据:

select * from staff where id>20 and age >40 or salary > 40000

6-13ThinkPHP5模型的删除操作:delete()和destroy()方法第6张

1.查询出数据:

<?php
namespace app\index\controller;
use app\index\model\Staff;
class Index
{
    public function index()
    {
        //select * from staff where id>20 and age >40 or salary > 40000
        $where=function($query)
        {
          $query->where('id>20')
                ->where('age','>',40)
                ->whereOr('salary>40000');
        };
        $result=Staff::all($where);
        dump($result);
    }
}

执行:

6-13ThinkPHP5模型的删除操作:delete()和destroy()方法第7张

查看原始数据

<?php
namespace app\index\controller;
use app\index\model\Staff;
class Index
{
    public function index()
    {
        //select * from staff where id>20 and age >40 or salary > 40000
        $where=function($query)
        {
          $query->where('id>20')
                ->where('age','>',40)
                ->whereOr('salary>40000');
        };
        $result=Staff::all($where);
        foreach ($result as $value)
        {
            dump($value->getData());
        }

    }
}

执行:

6-13ThinkPHP5模型的删除操作:delete()和destroy()方法第8张

2.删除数据

<?php
namespace app\index\controller;
use app\index\model\Staff;
class Index
{
    public function index()
    {
        //select * from staff where id>20 and age >40 or salary > 40000
        $where=function($query)
        {
          $query->where('id>20')
                ->where('age','>',40)
                ->whereOr('salary>40000');
        };
        $affected=Staff::destroy($where);
        dump($affected);
    }
}

执行:

6-13ThinkPHP5模型的删除操作:delete()和destroy()方法第9张

此时韦一笑,岳不群2号被删除

6-13ThinkPHP5模型的删除操作:delete()和destroy()方法第10张


6-13ThinkPHP5模型的删除操作:delete()和destroy()方法第11张


刹渤搬涤伦歼叉蔑洗梦泡糖差