When the author wrote a simple interface to create a problem in the project, he accidentally stepped on the thinkphp's two pits. It's called a pit, but it's not familiar to the document. The interface code is as follows:
Public Function Createproblems () { $problems = I (' json. '); if (empty ($problems)) { $this->error ($problems, ' JSON format does not conform to specification '); } foreach ($problems as $problem) { $data = D (' problem ')->create ($problem, self::op_insert); if (! $data) { $this->error ($problem, D (' Problem ')->geterror ()); } $temp [] = $data; } $ret = D (' Problem ', ' Service ')->addproblems ($temp); if ($ret = = = False) { $this->error (null, ' Import failed '); } $this->success (null);}
The function of interface completion is the batch creation problem, the parameter is the JSON array, the Addproblem () method is a addall operation.
First PIT-Auto fill
Using autofill may overwrite form submission items. The purpose of this is to prevent the form from illegally submitting fields. When you create a data object by using the model class's creation method, the form data is processed automatically.
The official document explicitly says AutoFill will overwrite the form, so even if you give specific values in the parameters you post, you may be overwritten after using the Create method. never mind!!!
-addall method of the second pit
Null values cannot appear in the AddAll method, otherwise the other data will move forward automatically, causing the add to fail. Example:
[ { "appId": 1, "ServiceId": 2, "CreateUser": null, "status": 1, "priority": 2 }]
Where the CreateUser field is null, and the SQL statement inserted becomes INSERT into Va_problem (AppId, ServiceId, CreateUser, status, Priority) VALUES (1, 2, 1, 2). The null value is gone, causing the insert to fail, which should be a bug for ThinkPHP3.2.3. This blog has a related discussion.
The process of introducing a pit
The Problemmodel inside has the CreateUser to do the automatic filling.
When creating a problem through the API, the auto-fill overrides first, so the CreateUser value in the form is invalidated, which is the first pit. Then, because AutoFill CreateUser calls the Get_username () function, the session (username) does not get a value through the API call, so the field after create becomes "CreateUser": null, which introduces a second pit.