Home > Article > Backend Development > Solution to insert the same data in Thinkphp3.2
The following editor will bring you an article that perfectly solves the problem of inserting the same data in Thinkphp3.2. The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor and take a look
Problem description
When I used TP3.2 to insert data today, in order to avoid inserting the same Data (the so-called same data has the same primary key or the same unique index field), the index I created is as shown below, the primary key index is an auto-increment field, and duplication is not possible, that is, the unique index may be duplicated. What I hope is If the three fields uid, year, mounth, and day are the same, the current record will be updated.
Solution to the problem
When we faced such a problem before, we You know, MySQL provides ON DUPLICATE KEY UPDATE or REPLACE INTO to solve this problem.
Use ON DUPLICATE KEY UPDATE
Before inserting data, there is only one record in the table, as shown below
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 INTO
The code is as follows:
First execute the following code to insert a piece of data
REPLACE INTO `work_log` ( `uid`, `year`, `mounth`, `day`, `status` ) VALUES (1, 2016, 6, 2, 1)The effect is as shown below Execute the following code again, the code inserted above will be updated
REPLACE INTO `work_log` ( `uid`, `year`, `mounth`, `day`, `status` ) VALUES (1, 2016, 6, 2, 5)The effect is as shown below The difference between ON DUPLICATE KEY UPDATE and REPLACE INTOWhen the same value appears, ON DUPLICATE KEY UPDATE updates the existing record, REPLACE INTO deletes the previous record, and then Insert new record.
Solution in Thinkphp3.2
In Thinkphp3.2, the same insert is processed through the third parameter of the add() function Data issues. 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 exactly the third parameter in the add method.
The above is the detailed content of Solution to insert the same data in Thinkphp3.2. For more information, please follow other related articles on the PHP Chinese website!