The following article brings you a perfect solution to the problem of inserting the same data in Thinkphp3.2. The content is quite good, so I will share it with you now and give it as a reference.
Problem description
When using TP3.2 to insert data today, in order to avoid inserting the same data (the so-called same data, its The primary key is the same or the fields of the unique index are the same). The index I created is as shown below. The primary key index is an auto-increment field. Duplication is impossible, that is, the unique index may be duplicated. What I want is uid, year, mounth, day. If the three fields appear 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();
The code is as follows:
First execute the following code to insert a piece of dataREPLACE INTO `work_log` ( `uid`, `year`, `mounth`, `day`, `status` ) VALUES (1, 2016, 6, 2, 1)
REPLACE INTO `work_log` ( `uid`, `year`, `mounth`, `day`, `status` ) VALUES (1, 2016, 6, 2, 5)
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.
Related recommendations:thinkphp3.2.3 version database addition, deletion, modification and query implementation code
The above is the detailed content of Perfectly solve the problem of inserting the same data in Thinkphp3.2. For more information, please follow other related articles on the PHP Chinese website!