When the author carefully uses the addAll method in ThinkPHP to write a simple interface for creating problems in the project, he accidentally stepped on the two pitfalls of ThinkPHP. It is called a pitfall, but it is actually unfamiliar with the document. The interface code is as follows:
Public function createProblems () {$ problems = I ('json. '); if (empty ($ problems) {$ this-> error ($ problems, 'json format does not comply with the Normal');} foreach ($ problems as $ problem) {$ data = D ('blem')-> create ($ Problem, self: OP_INSERT); if (! $ Data) {$ this-> error ($ problem, D ('blem')-> getError () ;}$ temp [] = $ data ;} $ ret = D ('blem', 'service')-> addProblems ($ temp); if ($ ret = false) {$ this-> error (null, 'import failed');} $ this-> success (null );}
The interface completes the function of batch creation. the parameter is a json Array, and the addProblem () method is an addAll operation.
First pitfall-automatic filling
Using auto-fill may overwrite the form to submit the project. The purpose is to prevent the form from submitting fields illegally. When a data object is created using the create method of the Model class, the form data is automatically processed.
The official documentation clearly states that automatic filling will overwrite the form, so even if the parameter you post gives a specific value, it may be overwritten after the create method is used.10 million notes !!!
The second pitfall-addAll method
The addAll method cannot contain a null value. otherwise, other data is automatically moved forward, causing the addition to fail. Example:
[ { "appId": 1, "serviceId": 2, "createUser":null, "status": 1, "priority": 2 }]
The createUser field is null, and the SQL statement during insertion will become insert into va_problem (appId, serviceId, createUser, status, priority) values (1, 2, 1, 2 ). The null value is missing, leading to insertion failure. This should be a bug in ThinkPHP3.2.3. This blog has related discussions.
Introduction process
In problemModel, createUser is automatically filled.
When an api is used to create a problem, auto-fill will first overwrite it, so the createUser value in the form is invalid, which is the first pitfall. Then, because createUser is automatically filled with the get_username () function called, the session (username) cannot get the value when calling the api, so after "create", the field becomes "createUser": null, introduced the second pitfall.