我正在使用 CakePHP 3 和 MySQL。
我想通过模型实现一个INSERT on DUPLICATE KEY UPDATE
akaupsert
查询。CakePHP 3
给定下表:
+----+----------+-----+
| id | username | age |
+----+----------+-----+
| 1 | admin | 33 |
| 2 | Timmy | 17 |
| 3 | Sally | 23 |
+----+----------+-----+
哪里id
是主键,username
是唯一索引
当我有以下值等待被更新时:
Felicia, 27
Timmy, 71
我希望在 upsert之后得到以下结果:
+----+----------+-----+
| id | username | age |
+----+----------+-----+
| 1 | admin | 33 |
| 2 | Timmy | 71 |
| 3 | Sally | 23 |
| 4 | Felicia | 27 |
+----+----------+-----+
我知道如何在 MySQL 查询中进行 upsert:
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 进行 upsert?
请告知我如何实施。