Tp5_模型实现数据库的增删改查

2019-03-19  本文已影响0人  ZSGZ_AD

首先创建一个模型:
在模块下创建model目录,创建模型文件,注意模型文件名和数据库保持一致.


image.png
<?php
namespace app\index\model;
use think\Model;

class Staff extends Model
{
    //模型创建成功
}
image.png image.png

1.创建数据

Staff::create([
         'name'=>'林平之','age'=>'21', 'salary'=>1200
       ]);

//创建数据的方式2

 $staff = new Staff();
        $data = [      
            'name' => '林平之',
            'age' => 21
        ];
        $staff->save($data);
image.png

2.更新数据


image.png

更新数据:

//方式1   -如果更新多条数据使用saveall data传入二维数组即可
 $staff = new Staff();
        $data = [
            'id' => '1014',
            'name' => '岳不群',
            'age' => 45
        ];

        $staff->isUpdate(true)->save($data);
        dump($staff->getData());
//方式2 -推荐
    $staff = new Staff();
        $data = [

            'name' => '岳不群',
            'age' => 51
        ];
        $where = ['id' => '1014'];
        $staff->save($data,$where);
image.png
  //update(更新数据,更新条件,允许更新的字段)      
       $data = ['name'=>'韦一笑','age'=>59,'salary'=>6600];
        $where = ['id'=>1013];//条件
        //复杂条件可以使用闭包
    //        $where = function ($query){
    //          $query ->where('id','=','1036');//相等 = 号可以省略  
    //        };
        $field = ['name','age']; //只允许更新的字段
        $result = Staff::update($data,$where,$field);
image.png

3.查询操作


image.png
image.png
image.png
  //find()和get()只会获取第一条数据
        $staff = new Staff;
        $where = function ($query){
          $query ->field(['name','salary'])
          ->where('salary','>',6000);
        };
        $result = $staff->find($where);
        dump($result->getData());
image.png
 //查询多条用select()或all()方法
  $staff = new Staff;
        $where = function ($query){
          $query ->field(['name','salary'])
          ->where('salary','>',6000);
        };
        $result = $staff->select($where);
        foreach ($result as $value){
            dump($value->getData());
        }
image.png

//使用模型静态类的方式访问:

$where = function ($query){
          $query ->field(['name','salary'])
          ->where('salary','>',6000);
        };

        $result = Staff::select($where);
        foreach ($result as $key => $value){
            echo '第'.($key+1).'条记录的姓名是:'.$value->name.',工资是:'.$value->salary.'<br>';
        }
image.png

4.删除操作


image.png
  //删除大于1012的数据 ,get和find方法获取一条数据,对应删除也只删除了第一条数据id位1013的数据
  $result = Staff::get(['id'=>['>',1012]]);
  $result -> delete();
image.png
  //多条语句的删除操作

where = function (query) {
query->where('id', '>', 1009) ->where('age', '>', 40) ->whereOr('salary', '>', 6000); }; // Staff::select(where); //查询结果
Staff::destory($where); //删除

上一篇 下一篇

猜你喜欢

热点阅读