如何在 CakePHP 3 中实现 INSERT ON DUPLICATE KEY UPDATE aka upsert?
我使用的是 CakePHP 3 和 MySQL.
I am using CakePHP 3 and MySQL.
我想通过 CakePHP 3
模型实现 INSERT on DUPLICATE KEY UPDATE
aka upsert
查询.
I would like to implement a INSERT on DUPLICATE KEY UPDATE
aka upsert
query via CakePHP 3
model.
鉴于下表:
+----+----------+-----+
| id | username | age |
+----+----------+-----+
| 1 | admin | 33 |
| 2 | Timmy | 17 |
| 3 | Sally | 23 |
+----+----------+-----+
其中 id
是主键,username
是唯一索引
where id
is Primary Key and username
is unique index
当我有以下值等待更新时:
When I have the following values awaiting to be upserted:
Felicia, 27
Timmy, 71
我希望在更新插入后得到以下结果:
I expect the following result after the upsert:
+----+----------+-----+
| id | username | age |
+----+----------+-----+
| 1 | admin | 33 |
| 2 | Timmy | 71 |
| 3 | Sally | 23 |
| 4 | Felicia | 27 |
+----+----------+-----+
我知道如何在 MySQL 查询中进行更新插入:
INSERT INTO `users` (`username`, `age`)
VALUES ('Felicia', 27), ('Timmy', 71)
ON DUPLICATE KEY UPDATE
`username`=VALUES(`username`),`age`=VALUES(`age`);
我知道如何在 CakePHP3 中的多个查询中执行此操作.
$newUsers = [
[
'username' => 'Felicia',
'age' => 27,
],
[
'username' => 'Timmy',
'age' => 71,
],
];
foreach ($newUsers as $newUser) {
$existingRecord = $this->Users->find()
->select(['id'])
->where(['username' => $newUser['username']])
->first();
if (empty($existingRecord)) {
$insertQuery = $this->Users->query();
$insertQuery->insert(array_keys($newUser))
->values($newUser)
->execute();
} else {
$updateQuery = $this->Users->query();
$updateQuery->update()
->set($newUser)
->where(['id' => $existingRecord->id])
->execute();
}
}
我想知道的是:
即使我使用链接,有没有办法在一行中使用 CakePHP 3 进行更新插入?
请告诉我如何实施.
推荐答案
使用 https://stackoverflow.com/上提供的答案a/24990944/80353,我想使用问题中给出的代码示例重新表述这一点.
Using the answer provided at https://stackoverflow.com/a/24990944/80353, I want to rephrase this using the code sample given in the question.
对以下记录运行 upsert
To run upsert on the following records
Felicia, 27
Timmy, 71
进入这张表
+----+----------+-----+
| id | username | age |
+----+----------+-----+
| 1 | admin | 33 |
| 2 | Timmy | 17 |
| 3 | Sally | 23 |
+----+----------+-----+
最好的方法是把它写成
$newUsers = [
[
'username' => 'Felicia',
'age' => 27,
],
[
'username' => 'Timmy',
'age' => 71,
],
];
$columns = array_keys($newUsers[0]);
$upsertQuery = $this->Users->query();
$upsertQuery->insert($columns);
// need to run clause('values') AFTER insert()
$upsertQuery->clause('values')->values($newUsers);
$upsertQuery->epilog('ON DUPLICATE KEY UPDATE `username`=VALUES(`username`), `age`=VALUES(`age`)')
->execute();
查看this了解有关<代码>结语
查看this了解如何在单个查询中编写插入多条记录的详细信息
Check this out for details on how to write insert multiple records in single query
相关文章