The data method of the Thinkphp curd method is also one of the consistent operations of the model class, which is used to set the value of the object currently being manipulated, and many developers are not accustomed to using this method today to explain how to use a good data method.
The specific usage is as follows:
1. Write operation
Typically, we create a data object by creating a method or assigning it, and then write to the database, for example:
$Model = D (' User ');
$Model->create ();
Here the specific automatic generation and validation judgment
$Model->add ();
or assign a value directly to a data object, for example:
$Model = M (' User ');
$Model->name = ' fleeting ';
$Model->email = ' thinkphp@qq.com ';
$Model->add ();
The data method then generates the object to be manipulated directly, for example:
$Model = M (' User ');
$data [' name '] = ' fleeting ';
$data [' email '] = ' thinkphp@qq.com ';
$Model->data ($data)->add ();
Note: If we use both the Create method and the data object, then the method invoked is valid .
The data method supports arrays, objects, and strings in the following ways:
$Model = M (' User ');
$obj = new StdClass;
$obj->name = ' fleeting ';
$obj->email = ' thinkphp@qq.com ';
$Model->data ($obj)->add ();
The string method is used as follows:
$Model = M (' User ');
$data = ' name= fleeting &email=thinkphp@qq.com ';
$Model->data ($data)->add ();
You can also add data to the Add method directly by passing in the data object, for example:
$Model = M (' User ');
$data [' name '] = ' fleeting ';
$data [' email '] = ' thinkphp@qq.com ';
$Model->add ($data);
But this way the data parameter can only use an array.
The data method, of course, can also be used to update information, for example:
$Model = M (' User ');
$data [' id '] = 8;
$data [' name '] = ' fleeting ';
$data [' email '] = ' thinkphp@qq.com ';
$Model->data ($data)->save ();
Of course, we can also use this directly:
$Model = M (' User ');
$data [' id '] = 8;
$data [' name '] = ' fleeting ';
$data [' email '] = ' thinkphp@qq.com ';
$Model->save ($data);
Similarly, the data parameter can only be passed in to the array at this time.
When you call the Save method to update the data, you automatically determine whether there is a primary key value in the current data object and, if so, automatically as the update condition. In other words, the following usage is equivalent to the above:
$Model = M (' User ');
$data [' name '] = ' fleeting ';
$data [' email '] = ' thinkphp@qq.com ';
$Model->data ($data)->where (' id=8 ')->save ();
2. Read operation
In addition to write operations, the data method can also be used to read the current object, for example:
$User = M (' User ');
$map [' name '] = ' fleeting ';
$User->where ($map)->find ();
Reads the current data object
$data = $User->data ();