TP5 Model function summary

*文
Release: 2023-03-18 08:12:01
Original
4777 people have browsed it

TP5 provides powerful Model functions, follow this article to find out.

Introduction

  1. tp5 model only performs business layer operations and does not perform specific link database SQL operations.

  2. think\db\Connection.php does the link database operation

  3. think\db\Builder.php does the create sql operation

  4. think\db\Query.php does data CURD operations

Function list

  1. Data automatic completion

  2. Automatic writing of timestamp

  3. Time field automatically formatted output field

  4. Field validator

  5. Auto-associated writing

  6. Read-only field

  7. Hidden field

  8. Event callback

  9. Soft delete

  10. Type conversion

Function details

1. Data automatic completion

   //设置自动完成的字段,支持键值对数组和索引数组
    //新增和更新时都会使用
    //如:['name'=>'zhangsan','sex'=>'男']
    // ['name','sex']
    protected $auto = [];    //新增 自动完成列表
    //只在新增数据的时候使用
    protected $insert = [];    //更新 自动完成列表
    //只在更新数据的时候使用
    protected $update = [];    //用来标记当前操作被修改的字段
    //如 ['name','sex']
    protected $change = [];    //依赖方法,model类会自动调用解析auto数组
    //我们只需配置auto数组即可
    protected function autoCompleteData($auto = []){}
Copy after login

After setting the auto field in the model, when updating or adding, it will first determine whether the field set in auto exists. In the updated field ($this->change)

If it exists, the fields and values ​​set in auto will not be used.

If it does not exist, the fields and values ​​set in auto will be added to this->data and add the field to this->change.

If auto is an index array, that is, only the field name is set, and the subfield value is not set, the field value will be queried in $this->data according to the field name, and added to Go to the attribute array to be updated.

The method for adding new data is create, the method for modifying data is update, the method for batch adding and modifying is saveAll, the final implementation of these methods is to call the save method

The saveAll method adds and modifies in batches. It does not combine SQL statements, but starts a transaction, then calls the save method, adds and modifies one by one, and finally commits the transaction.

During the update operation, the model will automatically check whether the values ​​of all fields in the data have been changed, and will only update the values ​​of the changed fields. Anything that has not been changed is ignored.

The functions of insert and update are similar to the functions of auto, except that auto is used whether it is new data or updated data, while the insert value is for new additions, and update is only for updates. If the same attributes are set, insert and update will overwrite the fields in auto.

2. Automatically write timestamp

   //是否需要自动写入时间戳
    //可以是字符串类型和boolean类型
    //字符串类型代表要写入的时间格式
    //如: 'Y-m-d H:i:s'
    //boolean类型就是true和false,代表是否开启
    //默认时间格式为int类型
    protected $autoWriteTimestamp;    //默认自动写入的字段有
    //创建时间和更新时间,他们对应的字段名分别是
    //create_time,和update_time
    //也可以在model里自己设置。
    protected $createTime = 'create_time';    protected $updateTime = 'update_time';
Copy after login

Configuration method

This configuration TP5 defaults to false and needs to be turned on manually

In the database configuration (database. php) to add global configuration.

   'auto_timestamp' => true
    //或者设置时间格式
    // 'auto_timestamp' => 'datatime'
Copy after login

Set in a separate model class

   protected $autoWriteTimestamp = true;    //或者设置时间格式
    // protected $autoWriteTimestamp = 'datatime';
Copy after login

The field type of knowledge timestamp/datetime/int

If your data field is not the default value, you can set it in your own Modify in the model.

   //如:
    protected $createTime = 'my_create_time_filed';    
    protected $updateTime = 'my_careate_time_field';
Copy after login

If you only need createTime but not updateTIme, you can turn off updateTIme in the model

   //如
    protected $updateTime = false;123
Copy after login

Opening and closing in the model only works for a single model. Do you want it to work globally? To be configured in the configuration file.

3. Time field automatic formatting output

   //输出格式
    protected $dateFormat;123
Copy after login

Configuration method

This configuration TP5 mode output format is 'Y-m-d H:i:s'

You can configure it yourself in the database configuration file (database.php). For example,

   'datetime_format' => 'Y/m/d H:i',12
Copy after login

can also be set in the model

   protected $dateFormat = 'Y/m/d H:i';12
Copy after login

4. Field validator

   //字段验证规则
    protected $validate = [];    //是否采用批量验证
    protected $batchValidate = false;    /**
     * 设置字段验证
     * @access public
     * @param array|string|bool $rule  验证规则 true表示自动读取验证器类
     * @param array             $msg   提示信息
     * @param bool              $batch 批量验证
     * @return $this
     */
    public function validate($rule = ture,$msg=[],$bath=false){}    /**
     * 自动验证数据
     * @access protected
     * @param array $data  验证数据
     * @param mixed $rule  验证规则
     * @param bool  $batch 批量验证
     * @return bool
     */
    public function validateData($data,$rule=null,$batch=null){}
Copy after login

Usage method

Configure field validation rules in the model, in New and update operations are common throughout the model.

// Advantages: You only need to set it once and it can be used universally
// Disadvantages: It cannot be set in a targeted manner
//For example: adding new users and editing user functions,
//New The password is added as a required item, and the password is optional when editing.
//So you cannot set the password verification rules in the model.
At this time, you can only set the password in the newly added action. Did the verification.

protected $validate = [        
        'rule' => [            
                'name' => 'require',            
                //多个规则可以是用字符串用|分隔
           //也可以使用数组['require','number','min'=>10,'max'=>80]
           //使用字符串配置要被使用explode('|',$rule)转化成数组,所以使用数组配置效率更高
           'age' => 'require|number|min:10|max:80',            
           'height' => 'between:100,200'
        ],        
       'msg' => [            
             'name' => 'name不能为空',            
             'age.require' => 'age不能没空',            
             'age.number' => 'age必须是一个数字',            
             'age.min' => 'age最小为10',            
             'age.max' => 'age最大为80',            
             'height' => 'height只能在100到200之间'
        ]
    ];
Copy after login

Call the think\Validate class during specific operations to implement

   //在类的头部,因为Validate文件。
    use think\Validate;    
    $validate = new Validate([     
       'name' => 'require',    
       'age' => 'require|number|min:10|max:80'
    ],[        
          'name' => 'name不能为空',        
          'age.require' => 'age不能没空',        
          'age.number' => 'age必须是一个数字',        
          'age.min' => 'age最小为10',        
          'age.max' => 'age最大为80',
    ]);    
    //使用check检查数据
    if($validate->check($data)){     
       echo '数据格式符合要求';
    }else{      
          //比如:name不能为空
        echo $validate->getError();
    }
Copy after login

Comparison

Use the first method to set the verification rules in the model, although the structure looks comparable Reasonable, but this method is less flexible because it is judged when saving. If the save fails, you don't know whether the data validation failed or the data insertion failed. Therefore, it is very troublesome to do prompt verification (because we return the prompts for data verification directly to the user, but generally we do not return the prompts for database operations to the user, so we have to make judgments after getting the results, so it is more troublesome to verify them first).

使用第二种方法在action里定义一个_validate的函数,专门用来做数据校验,这中方法比较灵活,而且他是在在保存数据之前做的校验,所以返回结果分的比较清楚,对用户的提示也比较清晰,代码可读性也比较好。

5. 自动关联写入

   // 关联对象
    protected $relation;    // 关联自动写入(关联的属性名)
    protectd $relationWrite = [];
Copy after login

暂时没有使用,后续再继续不补充。

6. 只读字段

   //用来保护那些不许要被更新的字段。
    //比如,创建时间
    //设置后再更新数据时,会字段过滤掉create_time字段
    //避免更新到数据库。
    protected $readonly = ['create_time'];
Copy after login

7. 隐藏字段

    //设置要隐藏的字段,
    //该设置只在toArray(),和subToArray()方法中起作用
    protected $hidden = [];    //相关方法
    public function hidden($hidden=[],$override=false){
    }
Copy after login

当使用toArray和subToArray获得数组数据时,使用hidden字段和hidden函数可以隐藏数组中的元素。如:

    //user表的属性字段(模拟操作)
    user_field = ['name','sex','age','height'];
Copy after login

在User模型中设置$hidden字段

   protected $hidden = ['age','height'];
    dump($User->toArray()); //只有name和sex字段。
    //也可以调用hidden方法隐藏字段
    //会有 name,age,height 三个字段
    dump($User->hidde(['sex'])->toArray()); 
    //只有name字段了
    //第二个参数标识是否合并 $this->hidden 
    dump($user->hidden(['sex'],true)->toArray());
Copy after login

8. 事件回调

支持的回调事件

before_insert 新增前

after_insert 新增后

before_update 更新前

after_update 更新后

before_write 写入前(新增和更新都会调用)

after_write 写入后(新增和更新都会调用)

before_delete 删除前

after_delete 删除后

注册的回调方法支持传入一个参数,当前示例模型对象,并且before_write,before_insert,before_update,before_delete返回false会结束执行。

使用方法

控制器里使用

   //支持给一个位置注册多个事件    
   User::event('before_insert',function($user){        
       if($user->status != 1){            
           return false;        
       }    
   });    
    //这个也会生效,回到函数为beforeInsert    
  User::event('before_insert','beforeInsert');
Copy after login

模型里使用

   //使用init方法统一注册模型事件
    class User extends Model{
        protected static function init(){
            User::event('before_insert',function($user){
                if($user->status != 1){                    
                    return false;
                }
            }            
            //注册第二个事件
            User::event('before_insert','beforeInsert');
        }
    }
Copy after login

原理

model类里有一个protected static $event = [];属性,注册的时间都存放在这个属性中。比如:

   $event = [        
          //模型名称
        'user' => [            
              //事件名称
            'before_insert' => ['callback_funciton','beforeInsert'],            
            'after_insert' => ['callback_function','afterInsert'],            
            'before_delete' => ['beforeDelete']
        ]
    ]
Copy after login

注册事件时,把所有的事件都保存在$event中了,然后在insert,update,delete等相应的位置调用即可。

9. 软删除

简介

在实际项目中,对数据频繁的使用删除操作可能会导致性能问题,软删除的作用就是给数据加上删除标记,而不是真正的删除,同时也便于需要的时候恢复数据。

设置方式

使用软删除功能需要引用SoftDelete trait;如:

   namespace app\index\model;    
   use think\Model;    
   use think\model\SoftDelete;    
   class User extends Model{
        // 使用SoftDelete
        // trait 的使用方式
        // 使用trait跟类的继承相似
        use SoftDelete;        
        //软删除标记的字段名
        protected $deleteTime = 'delete_time';
    }
Copy after login

dateteTIme属性用于标记数据表里的软删除字段,TP5里的软删除使用的是int类型,默认值为null(这个很重要,因为查询的时候是用delete_time is not null 来查询的),用于记录删除时间。

可以用类型转换指定软删除的字段类型,建议数据表里的所有时间字段使用同一种数据类型。

使用方式

在model中设置好后,就可以直接使用了

   //软删除
    User::destory(1);    
    //真删除
    User::destory(1,true);    
    //软删除
    $user = User::get(1);    
    $user->delete();    
    //真删除
    $user->delete(true);
Copy after login

默认情况下,查询出来的数据是不包括软删除的数据的,如果想要查询包括软删除的数据,可以使用下面的方式。

    User::withTrashed()->find();
   User::withTrashed()->select();
Copy after login

如果仅需要查询软删除的数据,可以这样:

    User::onlyTranshed()->find();
   User::onlyTranshed()->select();
Copy after login

10. 类型转换

TP5支持给数据表中的字段设置类型,并会在读取和写入的时候自动转换。如:

   class User extends Model{
        protected $type = [            
            'status' => 'integer',            
            'score' => 'float',            
            'login_timme' => 'datetime',            
            'info' => 'array'
        ];
    }
Copy after login

使用示例

   $user = new User;    
    $user->status = '1';    
    $user->score = '90.50';    
    $user->birthday = '2015/5/1';    
    $user->info = ['a'=>1,'b'=>2];    
    $user->save();
    var_dump($user->status); // int 1
    var_dump($user->score); // float 90.5;
    var_dump($user->birthday); // string '2015-05-01 00:00:00'
    var_dump($user->info);// array (size=2) 'a' => int 1  'b' => int 2
Copy after login

注意: 如果制定为时间戳类型(timestamp)的话,该字段会在写入的时候自动调用strtotime函数生成对应的时间戳,输出是自动使用dateFormat格式化时间戳,默认格式为Y:m:d H:i:s,如果想要改变输出格式,可以如下:

   class User extends Model{
        protected $dataFormat = 'Y/m/d';        
        protected $type = [            
            'status' => 'integer',            
            'score' => 'float',            
            'birthday' => 'timestemp'//时间戳格式
        ];
    }
Copy after login

或者如下:

   class User extends Model{        
       protected $type = [            
           'status' => 'integer',            
           'socre' => 'float',            
           'birthday' => 'timestemp:Y/m/d'//写入时间戳,读取按照Y/m/d的格式来格式化输出。        
       ]; 
      }
Copy after login

  

相关阅读:

最详细的ThinkPHP5自定义分页类教程

thinkphp执行原生SQL语句的实现方法.

thinkphp5实现分页功能的方法介绍


The above is the detailed content of TP5 Model function summary. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template