How to implement INSERT ON DUPLICATE KEY UPDATE aka upsert in CakePHP 3?

核能气质少年 提交于 2019-12-24 03:38:06

问题


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.


回答1:


Using the answer provided at https://stackoverflow.com/a/24990944/80353, I want to rephrase this using the code sample given in the question.

To run upsert on the following records

Felicia, 27
Timmy, 71

into this table

+----+----------+-----+
| id | username | age |
+----+----------+-----+
|  1 | admin    |  33 |
|  2 | Timmy    |  17 |
|  3 | Sally    |  23 |
+----+----------+-----+

the best way is to write it as

$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();

Check this out for details about epilog

Check this out for details on how to write insert multiple records in single query



来源:https://stackoverflow.com/questions/26572523/how-to-implement-insert-on-duplicate-key-update-aka-upsert-in-cakephp-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!