Here's a perfect solution to the problem of inserting the same data into the Thinkphp3.2. Content is very good, now share to everyone, but also for everyone to make a reference.
Problem description
Today when inserting data using TP3.2, in order to avoid inserting the same data (so-called same data, whose primary key is the same as the field of the unique index), I create indexes such as the primary key index as the self-increment field, it is impossible to duplicate, that is, the unique index may be duplicated, I want to be uid,year, Mounth,day the three fields appear the same, the current record is updated.
Problem-solving approach
Before facing such a problem, we knew that MySQL provided on DUPLICATE KEY Update or replace into to solve.
Using the on DUPLICATE KEY UPDATE
Before inserting data, a record in the table, such as
The SQL statement is as follows, and when the record is inserted, it is the same as the one already in the table, and the record is updated, otherwise it is inserted.
INSERT into ' work_log ' (' uid ', ' Year ', ' Mounth ', ' Day ', ' status ') VALUES (1, 6, 3, 1) on DUPLICATE KEY UPDATE ' status ' = VALUES (' status '), ' updated_ts ' = Now ();
Use Replace into
The code is as follows:
Insert a piece of data by executing the following code first
REPLACE into ' work_log ' (' uid ', ' Year ', ' Mounth ', ' Day ', ' status ') VALUES (1, 2016, 6, 2, 1)
Effects such as
Execute the following code again to update the code you inserted above
REPLACE into ' work_log ' (' uid ', ' Year ', ' Mounth ', ' Day ', ' status ') VALUES (1, 2016, 6, 2, 5)
Effects such as
On DUPLICATE KEY update vs. replace into difference
When the same value occurs, on DUPLICATE KEY update is the update of the existing record, REPLACE into is the record before the deletion, and then the new record is inserted.
Solutions in Thinkphp3.2
In Thinkphp3.2, the problem of inserting the same data is handled by the third parameter of the Add () function.
Model.class.PHP in the Add () method, called the Insert method in Db.class.php, in the Insert method, we can see the following code:
Where $replace is exactly the third parameter in the Add method.
Related recommendations:
thinkphp3.2.3 version of the database additions and deletions to change the implementation code