模型简介
- /*
- Navicat MySQL Data Transfer
-
- Source Server : 127.0.0.1
- Source Server Version : 50726
- Source Host : localhost:3306
- Source Database : tp6
-
- Target Server Type : MYSQL
- Target Server Version : 50726
- File Encoding : 65001
-
- Date: 2020-05-28 11:45:22
- */
-
- SET FOREIGN_KEY_CHECKS=0;
-
- -- ----------------------------
- -- Table structure for user
- -- ----------------------------
- DROP TABLE IF EXISTS `user`;
- CREATE TABLE `user` (
- `user_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
- `name` varchar(30) COLLATE utf8mb4_unicode_ci NOT NULL,
- `age` tinyint(3) unsigned NOT NULL,
- `email` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL,
- `password` varchar(32) COLLATE utf8mb4_unicode_ci NOT NULL,
- PRIMARY KEY (`user_id`)
- ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-
- -- ----------------------------
- -- Records of user
- -- ----------------------------
- INSERT INTO `user` VALUES ('1', '韦小宝', '35', 'wexiaobao@php.cn', 'e10adc3949ba59abbe56e057f20f883e');
- INSERT INTO `user` VALUES ('2', '小龙女', '50', 'xln@php.cn', 'e10adc3949ba59abbe56e057f20f883e');
- INSERT INTO `user` VALUES ('3', '过儿', '25', 'ge@php.cn', 'e10adc3949ba59abbe56e057f20f883e');
- INSERT INTO `user` VALUES ('4', '郭大侠', '45', 'gj@php.cn', 'e10adc3949ba59abbe56e057f20f883e');
第1步:( app\index\model\User.php )新建model文件目录,并在其下方新建一个类文件User.php内容如下
- <?php
- namespace app\index\model;
-
- use think\Model;
-
- class User extends Model{
-
- protected $table = 'user';
- protected $pk = 'user_id';
-
- }
第2步:( app\index\controller\ModelTest.php )在controller文件目录下,新建一个类文件 ModelTest .php内容如下
- <?php
- namespace app\index\controller;
-
- use app\index\model\User;
-
-
- class ModelTest{
-
-
- //模型对象
- public function demo1()
- {
-
- //创建模型对象
- $user = new User();
-
- //查询一条数据
- $res = $user->db()->find(1);
- dump($res);
-
- //查询所有数据
- //$res = $user->db()->select();
-
- //测试打印输出对象方式 dump()/var_dump()
- // var_dump 打印输出对象:var_dump($user);
- // dump($res);
- // dump(gettype($user));
- }
-
- //依赖注入
- public function demo2(User $user)
- {
-
- $res = $user->db()->find(3);
- //dump($res);
- var_dump($res);
-
- echo '<hr>';
- echo $res['name'];
-
- echo '<br/>';
- echo $res->name;
-
- }
-
-
-
-
- //1.新增操作:create():参数就是要新增的数据,返回当前模型对象
-
- public function insert()
- {
- $data = ['name'=> '乔峰','age'=>40,'email'=>'qiaofeng@php.cn','password'=>Md5('123')]; // 根据数据库字段设置,也可以用 sha1('123')
-
- $user = User::create($data);
-
- $insertId = $user['user_id'];
-
- return '新增成功,新增记录的主键ID是:'.$insertId;
-
- }
-
-
-
- //2.查询操作
- //在tp6中,删除了传统的get/all,直接用db()来调用Query类中的方法完成
-
- public function select(User $user)
- {
- //单条 查看对象:var_dump($user->db());
- echo '打印单条数据:';
- $res1 = $user->db()->find(3);
- dump($res1);
-
- echo '<hr>';
- echo '打印全部数据:';
-
- //all() 根据条件 where() 打印出年龄大于30的所有数据
- $res2 = $user->db()->where('age','>',30)->select();
- dump($res2);
- }
-
-
-
- //3.更新操作:update
- public function update()
- {
- $user = User::update(['age'=>50],['user_id'=>2]);
- return '年龄已经被更新成:'.$user['age'];
-
- }
-
-
- // 4.删除操作:destroy():返回布尔值
-
- public function delete()
- {
-
- //删除user_id 等于 5的数据记录
-
- //删除方式1:静态方法方式
- // $res = User::destroy(['user_id'=>5]);
-
- //删除方式2:闭包方式,根据条件,删除user_id 等于5的记录
- $res = User::destroy( function($query){
- $query->where('user_id',5); //凡是使用静态方法的,都可以用闭包方式传递参数,例如:User::destroy和User::update
- });
- return $res ? '删除成功':'删除失败';
-
- }
- }
运行结果截图
总结
模型基本操作一
创建模型类: 类名与数据库同名
实例化方式: 类方法中实例化,依赖注入(外部实例化)
常用操作: CURD(增删改查)
调用方式:
实例方法: 必须通过模型对象调用
静态方法: 直接用模型类调用(推荐)
模型基本操作二
查询:db()
新增:create()
更新: update()
删除: destory()
使用:
- //引用
- use app\services\table\model\Guestbook;
-
- //实例化
- $Guestbook = new GuestbookModel();
-
- //写入默认数据库(protected $connection = 'enterprise_cold')的表
- $rs=$Guestbook->save([
- 'username' => 'thinkphp',
- 'phone' => '1364002250'
- ]);
-
- //写入其它数据库(enterprise)中,不使用默认值
- $rs=$Guestbook->connect('enterprise')->save([
- 'username' => 'thinkphp',
- 'phone' => '1364002250'
- ]);
实际例子:
1.分布式数据库插入多表数据,有事务需要回滚
调用:
- //引用
- use app\services\table\model\Guestbook;
-
- //静态调用
- $returnData = Guestbook::saveGuestbook($postdata);
-
表对应模型文件代码:
- <?php
- namespace app\services\table\model;
- use think\Model;
- use think\facade\Db;
- use app\services\table\validate\GuestbookValidate;
-
- class Guestbook extends Model
- {
- protected $name = 'guestbook'; //表名
- protected $connection = 'enterprise_cold';//数据库的连接
-
-
- protected $autoWriteTimestamp = 'int';
- protected $createTime = 'time';
- // protected $updateTime = 'utime';
-
- // 设置字段信息
- protected $schema = [
- 'id' => 'int',
- 'uid' => 'bigint',//(唯一:前端用户取得电脑MAC转为十制进数字)
- 'enterprise_id' => 'int',
- 'phone' => 'string',
- 'username' => 'string',
- 'content' => 'string',
- 'gid' => 'int',
- 'sid' => 'int',
- 'wx' => 'string',
- 'email' => 'string',
- 'qq' => 'int',
- 'url' => 'string',
- 'ip' => 'string',
- 'type' => 'int',
- 'hide' => 'int',
- 'deleted' => 'int',
- 'deleted_time' => 'int',
- 'deleted_userid' => 'int',
- 'time' => 'int',
- ];
-
- /**
- * @name 保存访客提交过来的留言
- * @method Model
- * @date 2021-11-19
- * @param 1 $postdata arr/必填 提交数组
- * @ruturn array
- */
- static public function saveGuestbook(array $postdata)
- {
- Db::connect('enterprise_cold')->startTrans();
- Db::connect('enterprise_heat')->startTrans();
- try {
-
- $postdata['enterprise_id'] = !empty($postdata['eid'])?$postdata['eid']:0;
-
- validate(GuestbookValidate::class)->scene('onlineserviceApi_tel')->check($postdata);
-
- // $eid = !empty($postdata['enterprise_id'])?$postdata['enterprise_id']:0;
- $enterpriseData = numberEncodeDecodeHashids('enterprise',$postdata['enterprise_id'],1);//解密
- if($enterpriseData['code']!=200){
- throw new \Exception("非法提交,互联网不是法外之地,请慎重!");
- }
- //客服分组ID
- if(!empty($postdata['gid'])){
- $enterpriseData = numberEncodeDecodeHashids('onlineservice_group',$postdata['gid'],1);//解密
- if($enterpriseData['code']!=200){
- throw new \Exception("非法提交,互联网不是法外之地,请慎重!");
- }
- }
- //客服ID
- if(!empty($postdata['sid'])){
- $enterpriseData = numberEncodeDecodeHashids('enterprise_userid',$postdata['sid'],1);//解密
- if($enterpriseData['code']!=200){
- throw new \Exception("非法提交,互联网不是法外之地,请慎重!");
- }
- }
-
- $postdata['enterprise_id'] = $enterpriseData['data'][0];
-
- //1.7天表、1个月表
- self::connect('enterprise_heat')->setSuffix('_7d')->save($postdata);//7天表
- self::connect('enterprise_heat')->setSuffix('_1m')->save($postdata);//1个月表
-
- //2.今年表 以前表
- (new static())->setSuffix('_1y')->save($postdata);//今年表
- (new static())->save($postdata);//以前表(所有数据表)
-
- $code=200;$msg="成功";
- Db::connect('enterprise_cold')->commit();
- Db::connect('enterprise_heat')->commit();
- } catch (\Exception $e) {
- Db::connect('enterprise_cold')->rollback();
- Db::connect('enterprise_heat')->rollback();
- $code=-200;$msg=$e->getMessage();
- }
- return ['code' => $code,'msg' =>$msg];
-
- }
-
- }
2.单库单表插入数据(有事就启用)
调用:
- //引用
- use app\services\table\model\Guestbook;
-
- //动态调用 要实例化
- $TaskLog =new TaskLog();
- $returnData = $TaskLog ->saveGuestbook($postdata);
表对应模型文件代码:
- <?php
- namespace app\services\table\model;
- use think\Model;
- use think\facade\Db;
- use app\services\table\validate\TaskLogValidate;
-
- /**
- * @name 任务日志
- * @method Model/POST/GET/
- * @date 2021-12-01
- */
- class TaskLog extends Model
- {
- protected $name = 'task_log'; //表名
- protected $connection = 'log';//数据库的连接
-
-
- protected $autoWriteTimestamp = 'int';
- protected $createTime = 'time';
- // protected $updateTime = 'utime';
-
- // 设置字段信息
- protected $schema = [
- 'id' => 'int',
- 'user_id' => 'int',
- 'enterprise_id' => 'int',
- 'title' => 'string',
- 'data' => 'string',
- 'content' => 'string',
- 'starttime' => 'int',
- 'endtime' => 'int',
- 'url' => 'string',
- 'state' => 'int',
- 'url' => 'string',
- 'type' => 'int',
- 'mold' => 'int',
- 'delay' => 'int',
- 'time' => 'int',
- ];
-
-
- /**
- * @name 保存访客提交过来的留言
- * @method Model
- * @date 2021-11-19
- * @param 1 $postdata arr/必填 提交数组
- * @ruturn array
- */
- public function DataSave(array $postdata)
- {
- // Db::connect($this->connection)->startTrans();//有回滚就启用
- try {
-
-
- // if(empty($postdata)){
- // throw new \Exception("提交数据为空!");
- // }
- $postdata['enterprise_id'] = !empty($postdata['eid'])?$postdata['eid']:0;
-
- validate(TaskLogValidate::class)->check($postdata);
-
- if(!empty($postdata['enterprise_id'])){
- $enterpriseData = numberEncodeDecodeHashids('enterprise',$postdata['enterprise_id'],1);//解密
- if($enterpriseData['code']!=200){
- throw new \Exception("非法提交,互联网不是法外之地,请慎重!");
- }
- $postdata['enterprise_id'] = $enterpriseData['data'][0];
- }
-
- $this->save($postdata);//以前表(所有数据表)
-
- $code=200;$msg="成功";
- // Db::connect($this->connection)->commit();
- } catch (\Exception $e) {
- // Db::connect($this->connection)->rollback();
- $code=-200;$msg=$e->getMessage();
- }
- return ['code' => $code,'msg' =>$msg];
-
- }
-
- }