SoFunction
Updated on 2025-03-10

Examples of the use of model model's getter, modifier, and soft-delete data operation of Thinkphp5.0 framework

This article describes the use of the model model of the Thinkphp5.0 framework to obtain, modify and soft delete data operations. Share it for your reference, as follows:

1. Getter

Use get+field name+Attr in model to modify the return value of the field.

The gender in the database is saved as 0 unknown, 1 male, 2 female, and the Chinese characters are returned when querying:

model:

//Change 012 of gender to unknown or male.  Female returnspublic function getSexAttr($val){
    switch($val){
      case '1' :
        return 'male';
      case '2':
        return 'female';
      default:
        return 'unknown';
    }
}
//Return after formatting the timestamppublic function getAddtimeAttr($val){
    if($val){
      return date('Y-m-d H:i:s',$val);
    }else{
      return $val;
    }
}

controller:

$res = TestUser::get(2);
dump($res->toArray());//Gender will be converted by modeldump($res->getData());//Return the original data

2. Model modifier:

Use set+field name+Attr in model to modify the field value, which is convenient for use when adding data.

Example, for example, passwords require MD5 encryption:

model:

//Storage after encrypting the password field//The first parameter is the password//The second parameter is the added data, optionalpublic function setPasswordAttr($val,$data){
    if($val === '') {
      return $val;
    }else{
      return md5($val.$data['email']);
    }
}

3. Automatic completion:

model:

// Fields that will be automatically completed when added and modifiedprotected $auto = ['addtime'];
public function setAddtimeAttr(){
    return time();
}

3. Automatically complete when adding data:

model:

protected $insert = ['addtime'];
public function setAddtimeAttr(){
    return time();
}

4. When modifying data, it will be automatically completed:

model:

protected $update = ['addtime'];
public function setAddtimeAttr(){
    return time();
}

5. Automatically complete time stamp

In the database configuration file, there is one:

// Automatically write timestamp fields'auto_timestamp' => false,

If enabled, the timestamps of all tables will be automatically completed, but this is not recommended. It is safer to set only where you need it.

For example, the timestamp of the user table is automatically completed, and it is set in the User model:

<?php
namespace app\index\model;
use think\Model;
class User extends Model{
  //Enable automatic completion time stamp function  protected $autoWriteTimestamp = true;
  //After turning on,  //When adding data, the fields that are automatically completed by default are: create_time and update_time.  //When modifying data, the default automatically completed field is: update_time.  //If the database does not have these two fields, an error will be reported  //If you do not want to use these two fields, you can make the following modifications  protected $createTime = 'addtime';//Modify the default add time field  protected $updateTime = 'updtime';//Modify the default modification time field protected $updateTime = false;//Set to false when this field is not needed}

6. Soft Deletion

Soft Deletion: When deleting a record, sometimes we need to fake deletion and mark the record deleted by modifying the status of a certain field.

model:

<?php
namespace app\index\model;
use think\Model;
use traits\model\SoftDelete;//Introduce soft deleted classesclass User extends Model{
  //Use soft delete  //When deletion, the default updated field is delete_time  use SoftDelete;
  //If you modify the default field name  protected $deleteTime = 'deltime';
}

Controller:

$res = User::destroy(1);//Soft Delete//Return the number of rows affecteddump($res);

After the deletion is performed, the delete_time field will be updated. If the update_time field is also enabled, the update_time field will also be updated.

// Get all data and filter out records whose delete_time is not null (that is, records that are soft deleted will not be displayed)//Note that the default value of the delete_time field should be set to null, and cannot be set to 0, otherwise page 0 will be regarded as soft deleted data$res = $model->select();
//If you need to obtain data containing soft deletes, use withTrashed(true).$res = User::withTrashed(true)->select();
//If you need to obtain soft deleted data$res = User::onlyTrashed()->select();
//Delete the record with id 15. If soft deletion is enabled, false deletion will be performed$res = User::destroy(15);
//If soft deletion is enabled, the data needs to be deleted truly without soft deletion//Destroy() The second parameter passes true$res = User::destroy(15,true);
//The delete() parameter passes true$userData = User::get(15);
$userData->delete(true);

For more information about thinkPHP related content, please check out the topic of this site:ThinkPHP Introduction Tutorial》、《Summary of the operation skills of thinkPHP templates》、《Summary of common methods of ThinkPHP》、《Codeigniter Introductory Tutorial》、《Advanced tutorial on CI (CodeIgniter) framework》、《Zend FrameWork Framework Introduction Tutorial"and"PHP template technical summary》。

I hope that the description in this article will be helpful to everyone's PHP programming based on the ThinkPHP framework.