Thinkphp3.2 perfectly solves the problem of inserting the same data in thinkphp3.2.
Problem description
When using TP3.2 to insert data today, in order to avoid inserting the same data (the same data has the same primary key or the same unique index field), the index I created is as follows, the primary key index is an auto-increment field, which cannot be repeated. That is, the unique index may be duplicated. If the fields uid, year, mounth, and day are the same, update the current record.
Solution
We know that MySQL provides on duplicate key update or replace into to solve this problem.
Use ON DUPLICATE KEY UPDATE
Before inserting data, the table contains a record, as shown in figure
The SQL statement is as follows. When a record is inserted, it is the same as the existing record in the Table. Otherwise, the record is inserted.
INSERT INTO `work_log` (`uid`,`year`,`mounth`,`day`,`status`) VALUES(1, 2016, 6, 3, 1) ON DUPLICATE KEY UPDATE `status` = VALUES(`status`),`updated_ts` = NOW();
Use REPLACE
The Code is as follows:
Run the following code to insert a data entry:
REPLACE INTO `work_log` (`uid`,`year`,`mounth`,`day`,`status`) VALUES(1, 2016, 6, 2, 1)
Results:
Execute the following code again to update the code inserted above.
REPLACE INTO `work_log` (`uid`,`year`,`mounth`,`day`,`status`) VALUES(1, 2016, 6, 2, 5)
Results:
Differences between on duplicate key update and REPLACE
When the same value is displayed, on duplicate key update updates existing records, replace into deletes previous records, and then inserts new records.
Thinkphp3.2 Solution
In Thinkphp3.2, the third parameter of the add () function is used to insert the same data.
The add () method in Model. class. PHP calls the insert method in Db. class. php. In the insert method, we can see the following code:
$ Replace is the third parameter in the add method.
The above is a perfect solution to the problem of inserting the same data in Thinkphp3.2, which is all the content shared by Alibaba Cloud xiaobian. I hope you can provide a reference and support for the customer's home.