Home  >  Article  >  PHP Framework  >  Detailed explanation of modifiers and auto-complete in thinkPHP5 model

Detailed explanation of modifiers and auto-complete in thinkPHP5 model

藏色散人
藏色散人forward
2021-02-11 10:13:463062browse

The following tutorial column will introduce you to the modifiers and auto-complete in thinkPHP5 model. I hope it will be helpful to those who need it!

1. Modifier

Detailed explanation of modifiers and auto-complete in thinkPHP5 model During the actual development process, some fields need to be modified when stored in the table, such as the password filled in when the user registers Encryption is required when storing in the table, hence the modifier.

Modifiers are similar to getters and need to be written in the model. The naming rule is set field name (according to camel case method) Attr.

Example: When adding a user, the user's password needs to be encrypted

Create a user table

CREATE TABLE `tp_user` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `username` varchar(60) NOT NULL DEFAULT '',
  `password` char(32) NOT NULL DEFAULT '',
  `mobile` varchar(15) NOT NULL DEFAULT '' COMMENT '用户手机号',
  `email` varchar(100) NOT NULL DEFAULT '',
  `sex` tinyint(3) NOT NULL DEFAULT '0' COMMENT '性别 0未知 1男 2女',
  `age` tinyint(3) unsigned NOT NULL DEFAULT '0',
  `time` int(10) NOT NULL DEFAULT '0' COMMENT '时间',
  `create_time` int(10) NOT NULL DEFAULT '0' COMMENT '创建时间',
  `update_time` int(10) NOT NULL DEFAULT '0' COMMENT '更新时间',
  `status` tinyint(3) NOT NULL DEFAULT '1' COMMENT '记录状态 -1删除 0禁用 1正常',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=12 DEFAULT CHARSET=utf8;

Add a password modifier to the model:

namespace app\index\model;
use think\Model;
class User extends Model{
    //密码的修改器
    public function setPasswordAttr($val){
        //此处做一些对用户传入值的处理
        return md5($val);
    }
}

In the controller Add user data:

namespace app\index\controller;
use think\Controller;
use app\index\model\User;
class Index extends Controller{
    public function index(){
        //模拟传入的post表单数据
        $data = [
            'username' => 'Emrys',
            'password' => 'emrys',
            'email' => 'emrys126.com',
            'mobile' => '13955555555',
            'sex' => 1,
            'age' => 18
        ];

        //添加用户数据
        $res = User::create($data);
        dump($res);
    }
}

After running, there are more records in the database, and the password field is the value changed by the password modifier.

2. Automatic completion

The table fields created in actual development basically have fields that need to be automatically completed, such as record creation time, update time, creation time, etc. Person ID (the ID of the logged-in user), etc. In this case, you need to use the auto-complete function of the table. Automatic completion includes three types: automatic completion during insertion and update, automatic completion during insertion, and automatic completion during update. The setting is to use

//插入和更新时均自动完成的字段
protected $auto = [];

//只在插入时自动完成的字段
protected $insert = [];

//只在更新时自动完成的字段
protected $update = [];

in the model to set the time field to be automatically completed during insertion and update. The create_time field is automatically completed when inserting, and the update_time field is automatically completed when updating. The automatic completion settings are as follows.

namespace app\index\model;
use think\Model;
class User extends Model{
	//自动完成,插入和更新时都自动执行
	protected $auto = [
		'time'
	];

	//只在插入时完成
	protected $insert = [
		'create_time'
	];

	//只在数据更新时完成
	protected $update = [
		'update_time'
	];

	//获取器
	public function getSexAttr($val){
		switch ($val) {
			case '1':
				return '男';
				break;
			case '2':
				return '女';
				break;
			default:
				return '保密';
				break;
		}
	}

	//密码的修改器
	public function setPasswordAttr($val){
		return md5($val);
	}

	//时间修改器
	public function setTimeAttr(){
		return time();
	}

	//创建时间修改器
	public function setCreateTimeAttr(){
		return time();
	}

	//更新时间修改器
	public function setUpdateTimeAttr(){
		return time();
	}
}

Add data and update data in the controller to complete the test.

namespace app\index\controller;
use think\Controller;
use app\index\model\User;
class Index extends Controller{
    public function index(){
        //模拟传入的post表单数据
        $data = [
            'username' => 'Emrys',
            'password' => 'emrys',
            'email' => 'emrys126.com',
            'mobile' => '13955555555',
            'sex' => 1,
            'age' => 18
        ];

        //添加用户数据
        $res = User::create($data);
        dump($res);
    }
}

The results of executing the three fields of time, create_time, and update_time in the above added data code are as shown in the figure below. , when adding data, both the time and create_time fields are inserted into the current time, and update_time is the default value 0.

Code for updating data in the controller:

namespace app\index\controller;
use think\Controller;
use app\index\model\User;
class Index extends Controller{
    public function index(){
        //更新数据
        $user = User::get(12);
        $user->age = 120;
        $res = $user->save();
        dump($res);
    }
}
Execution After the update data code above, the current time is added to the update_time field, the value of the time field is also updated to the current time, and the value of create_time remains unchanged.

## Using modifiers to implement the auto-complete function requires adding modifiers for each field in each model, which results in bloated code. tp5 has a special configuration for this. Change the auto_timestamp = false item in the database connection configuration file database.php to true to automatically complete create_time and update_time in each table. Since create_time and update_time fields do not necessarily exist in every table, tp5 also provides methods to configure them in the model.

//开启自动写入时间戳
protected $autoWriteTimestamp = true;

//默认的时间戳是create_time和update_time,可通过如下进行修改。如果不想在插入或更新数据时添加该字段的值,则设置为false
protected $createTime = false;
protected $updateTime = '这里是真实表中的更新时间字段';

The above is the detailed content of Detailed explanation of modifiers and auto-complete in thinkPHP5 model. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete