Summary of common operation examples of TP5 framework model

Time:2021-2-14

This paper describes the common operations of TP5 framework model with examples. The details are as follows:

  • Use model to query data, add data, modify data and delete data
  • Aggregation operation
  • Getter, modifier
  • Automatically add time stamp (creation time, modification time)
  • Soft delete

1. Using model to query data

$res = user:: get (1); // get the data with the primary key of 1 and get an object
 
$res = $res - > toarray(); // convert object to array
 
Dump ($res - > name); // get the value of the name field in $res
//Using the closure function to query the record with id = 1
$res = User::get(function($query){
  $query->where("id","eq",1)
     ->field('name')
});
$res = User::where("id",10)->value('name');
$res = User::where("id",10)->field('name')->find();
 
$res = user:: column ('email '); // query all email field values    
$res = user:: where ("Id", ">", 5) - > select(); // query all records with ID greater than 5
$res = user:: all ('1,2 '); // query records with primary key equal to 1 or 2
Foreach ($res as $VAL) // convert to array
{
  dump($val->toArray());
}
//Using closure function to query records with ID < 5
$res = User::get(function($query){
  $query->where("id","<",5)
     ->field('name')
});

2. Using model to add data

$res = User::create([
  'name' => 'yulong',
  'pwd' => '123'
], true); // when the second parameter is true, only the existing fields in the data table will be added, and no error will be reported. Otherwise, the default value is false;;; true can also be replaced with an array in which the fields in the data table are stored, indicating that only the fields in the array are allowed to add data
$res - > ID; // self increasing ID added this time
dump($res);
$usermodel = new User;
$res = $usermodel
  ->Allowfield (true) // only the fields existing in the data table can be added, or they can be written as arrays
  ->save([
    'name' => 'yulong',
    'pwd' => '123'
  ]);
 
Dump ($res - > ID); // get the self increasing ID of the newly added data
$usermodel = new User;
$res = $usermodel - > saveall ([// save multiple data at a time)
  'name' => 'yulong001',
  'name' => 'yulong002'
]);
 
dump($ers);

3. Update data with model

$res = User::update([
  'name' => 'yulong002'
], ['id '= > 1]); // update the record with id = 1
 
 $res = User::update([
  'name' => 'yulong002'
],function(){
  $query - > where ("Id", "lt", 5); // update the record with ID < 5 by using the closure function
}); 
 
 
dump($res);
$res = user:: where ("Id", "<", 6) // the return value is the number of rows of the updated data
    ->update([
       'name' => 'hahahaha'
      ]);

4. Using model to delete data

$res = user:: destination (1); // delete the record with primary key 1, return the number of rows affecting the data, or pass an array
 
 
$usermodel = User::get(1);
$res    = $usermodel->delete();
 
 
$res = user:: where ("Id", 5) - > delete(); // where() has three parameters, field value, condition and numeric value
 
dump($res);

5. Aggregate operations using model

$res = user:: where ("Id", ">", 5) - > count(); // query the number of records with ID greater than 5
 
//Max can be replaced by other parameters such as min / sum / AVG
$res = user:: Max ('num '); // query the maximum value in the num field
$res = user:: where ("Id", "<", 5) - > max ('num '); // the maximum value of num in the record with ID < 5

6. Using model elicitor

//model 
//Method name: get field name attr
//Use $res - > getdata() to get the original data in the controller
 
public function getSexSttr($val){
  switch($val){
    case '1':
      Return "male";
      break;
    case '2';
      Return 'female';
      break;
    default:
      Return 'unknown';
      break;
  }
}

7. Using the model modifier

//Model modifier name set field name attr
//Modifier function: when adding fields to the database, the controller writes the unprocessed data, and writes the data processing method in the modifier of the model, so the data added to the database is the processed data
public function setPwdAttr($val){
  return md5($val);
}
 
//$Val represents PWD field and $data represents all received data. The returned value is PWD + email 
public function setPwdAttr($val,$data){
  return $val.$data['email'];
}

8. Automatically add time stamp to database

//Automatically add a timestamp to the time field
public function setTimeAttr(){
  return time();
}
 
//Changes when data is added
protected $insert = [ 'time_ Insert ']; // set fields
Public function settimeinsertattr() {// sets the field value to the current time
  return time();
}
 
//Changes when updating data
protected $update = [ 'time_ Update ']; // set fields
Public function settimeupdateattr() {// sets the field value to the current time
  return time();
}

9. Model timestamp

//Field create in database_ time update_ time
//  database.php  Change configuration 'auto' in_ timeStamp' => true
//This method is not recommended, because if there is no corresponding field in your database table, the program may report an error
//You can add attributes to a model individually 
 
Protected $autowritetimestamp = true; // enable auto add timestamp
 
protected $createTime = 'create_ At '; // set the field to be written when creating. The value can be false. Close the operation
protedted $updateTime = 'update_ At '; // set the field to be written when creating and updating. The value can be false. Close the operation

10. Soft delete

// model
//Field delete in data table_ The default value can be null
 
Use traits / model / softdelete; // classes that use soft delete
 
class User extends Model
{
  Use softdelete; // at the beginning of the class, use softdelete; 
  protected $deleteTime = 'delete_ At '; // set the soft delete field. The default value is delete_ time
}
 
 
$res = user:: Destroy (3, true); // delete the record with primary key 3. When the second parameter is true, it is not soft delete, but TM delete
 
$ress = User::get(4);
$res = $ress - > delete (true); // when delete() has no value, it is soft deletion; when the value is true, it is true deletion of TM
 
//The controller gets the soft deleted record
$res = user:: withtrapped (true) - > find (1); // get the soft deleted record with ID 1
Dump ($res - > getdata()); // get the original data
 
$res = user:: onlytrashed() - > select(); // get all soft deleted data

For more information about ThinkPHP, interested readers can check out the following topics: introduction to ThinkPHP, summary of operation skills of ThinkPHP template, summary of common methods of ThinkPHP, introduction to CodeIgniter, CI (CodeIgniter) framework advanced course, Zend framework introduction course and PHP template technology summary.

I hope this article will be helpful to the design of PHP program based on ThinkPHP framework.

Recommended Today

Redis persistence and memory optimization

Springboot real e-commerce project mall4j( https://gitee.com/gz-yami/mall4j ) Redis persistence and memory optimization Some persistence and memory optimization operations are carried out through the configuration file of redis. If there are any errors, you are welcome to guide. 1. Why persistence If the user data is saved to memory, the memory data will be cleared when […]