Tp5_模型实现数据库的增删改查
2019-03-19 本文已影响0人
ZSGZ_AD
首先创建一个模型:
在模块下创建model目录,创建模型文件,注意模型文件名和数据库保持一致.

<?php
namespace app\index\model;
use think\Model;
class Staff extends Model
{
//模型创建成功
}


1.创建数据
Staff::create([
'name'=>'林平之','age'=>'21', 'salary'=>1200
]);
//创建数据的方式2
$staff = new Staff();
$data = [
'name' => '林平之',
'age' => 21
];
$staff->save($data);

2.更新数据

更新数据:
//方式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);

//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);

3.查询操作



//find()和get()只会获取第一条数据
$staff = new Staff;
$where = function ($query){
$query ->field(['name','salary'])
->where('salary','>',6000);
};
$result = $staff->find($where);
dump($result->getData());

//查询多条用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());
}

//使用模型静态类的方式访问:
$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>';
}

4.删除操作

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

//多条语句的删除操作
query) {
where); //查询结果
Staff::destory($where); //删除