查询构造器中的增删改查操作

Original 2019-03-14 22:34:35 230
abstract:<?php /**  * 查询构造器的操作  */ namespace app\index\controller; use think\Db; class Query {    //读操作返回的是二维数组,没有返回的书空数组     //写操作返回的是受影响记录
<?php
/**
 * 查询构造器的操作
 */

namespace app\index\controller;
use think\Db;
class Query
{
   //读操作返回的是二维数组,没有返回的书空数组
    //写操作返回的是受影响记录的数量,没有返回的是0
    public function find()
    {
        //查询单条记录
        $res = Db::table('user')
            ->field(['name','phone'])//以数组的方式传递参数
            ->where('id','>',4)
            ->find();
        dump($res);
    }
    public function  select()
    {
        //查询满足条件的多条记录
        $res = Db::table('user')
            ->field(['name','age','phone'])
            ->where('age','>',40)
            ->order('id', 'DESC')
            ->limit(4)
            ->select();
        dump($res);
    }
    public function insert()
    {
        //新增单条记录
        $data = ['name'=>'大爷爷','sex'=>0,'age'=>78,'phone'=>32432435];
        //$num = Db::table('user')->insert($data);
        //$id = Db::getLastInsID();//返回受影响记录的id

        //data($data):将要处理的数据打包$option[]
        //insertGetId() == insert()+getLastInsID()
        //$id =Db::table('user')->insertGetId($data);

        //一般我们要将数据打包,在终极方法里面不传参数
        //$num = Db::table('user')->data($data)->insert();
        //$id=Db::getLastInsID();

        //新增多条记录
        $data = [
            ['name'=>'刘备','sex'=>0,'age'=>34],
            ['name'=>'张飞','sex'=>0,'age'=>45],
            ['name'=>'孙二娘','sex'=>1,'age'=>65]
        ];
        $num = Db::table('user')->data($data)->insertAll();
        return $num;

    }
    public function update()
    {
        //更新操作必须是基于前置查询,不允许无条件更新
        $num = Db::table('user')
            ->where('id','>=',11)
            ->where('sex',0)
            ->data(['age'=>Db::raw('age-10')])//Db::raw()拿到数据库中的原数据进行计算
            ->update();
        return $num ? '更新成功'.$num.'条记录' : '没有记录被更新';
    }
    public function delete()
    {
        /*$num = Db::table('user')
            ->where('id','>',11)
            ->delete();*/

        $num = Db::table('diector')->delete(true);//清空数据表中的所有数据
        return $num ? '成功删除'.$num.'条记录' : '没有记录被删除';
        //删除数据是一个危险操作,建议使用软删除来实现
        //在实际开发中,尽可能不要在控制器中直接操作数据库,而是在用模型来实现
    }
}


Correcting teacher:查无此人Correction time:2019-03-15 09:17:54
Teacher's summary:完成的不错。增删查改是php最基础的操作,继续加油

Release Notes

Popular Entries