Detailed Explanation of data Method of ThinkPHP CURD Method

  • 2021-07-01 06:53:40
  • OfStack

data method of ThinkPHP CURD method is also one of the coherent operation methods of model class, which is used to set the value of the data object to be operated at present, but many developers are not used to using this method. Today, let's explain how to make good use of data method.

The specific usage is as follows:

1. Write

Usually, we generate data objects through create method or assignment, and then write them to the database, for example:


$Model = D('User');
$Model->create();
 //  The specific automatic generation and verification judgments are skipped here 
$Model->add();

Or directly assign values to data objects, such as:


$Model = M('User');
$Model->name = ' Fleeting time ';
$Model->email = 'thinkphp@qq.com';
$Model->add();

Then the data method directly generates the data object to be manipulated, for example:


$Model = M('User');
$data['name'] = ' Fleeting time ';
$data['email'] = 'thinkphp@qq.com';
$Model->data($data)->add();

Note: If we use both the create method and the data method to create the data object, the method called later is valid.

The data method supports arrays, objects, and strings as follows:


$Model = M('User');
$obj = new stdClass;
$obj->name = ' Fleeting time ';
$obj->email = 'thinkphp@qq.com';
$Model->data($obj)->add();

The string mode is used as follows:


$Model = M('User');
$data = 'name= Fleeting time &email=thinkphp@qq.com';
$Model->data($data)->add();

You can also add data directly by passing in a data object in the add method, for example:


$Model = M('User');
$data['name'] = ' Fleeting time ';
$data['email'] = 'thinkphp@qq.com';
$Model->add($data);

However, in this way, only arrays can be used for data parameters.

Of course, the data method can also be used to update data, for example:


$Model = M('User');
$data['id'] = 8;
$data['name'] = ' Fleeting time ';
$data['email'] = 'thinkphp@qq.com';
$Model->data($data)->save();

Of course, we can also use it directly:


$Model = M('User');
$data['id'] = 8;
$data['name'] = ' Fleeting time ';
$data['email'] = 'thinkphp@qq.com';
$Model->save($data);

Similarly, the data parameter can only be passed into the array at this time.

When calling save method to update data, it will automatically judge whether there is a primary key value in the current data object, and if so, it will be automatically used as an update condition. That is, the following usage is equivalent to the above:


$Model = M('User');
$data['name'] = ' Fleeting time ';
$data['email'] = 'thinkphp@qq.com';
$Model->data($data)->where('id=8')->save();

2. Read

In addition to write operations, the data method can also be used to read the current data object, for example:


$User = M('User');
$map['name'] = ' Fleeting time ';
$User->where($map)->find();
 //  Read the current data object 
$data = $User->data();


Related articles: