I am using CakePHP 3 and MySQL.
I would like to implement a INSERT on DUPLICATE KEY UPDATE aka upsert query via CakePHP 3 model.
Given the following table:
+----+----------+-----+
| id | username | age |
+----+----------+-----+
| 1 | admin | 33 |
| 2 | Timmy | 17 |
| 3 | Sally | 23 |
+----+----------+-----+
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 |
+----+----------+-----+
I know how to do upsert in MySQL query:
INSERT INTO `users` (`username`, `age`)
VALUES ('Felicia', 27), ('Timmy', 71)
ON DUPLICATE KEY UPDATE
`username`=VALUES(`username`),`age`=VALUES(`age`);
I know how to do this in more than a single query in 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();
}
}
What I want to know is :
is there a way to do upsert using CakePHP 3 in a single line even if I use chaining?
Please advise how do I implement that.