Home  >  Article  >  Backend Development  >  Solution to insert the same data in Thinkphp3.2

Solution to insert the same data in Thinkphp3.2

巴扎黑
巴扎黑Original
2018-05-22 15:55:511551browse

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

##The SQL statement is as follows , when inserting a record, if it is the same as the existing record in the table, the new record will be updated, otherwise the record will be 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 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 INTO

When 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn