Welcome Guest, Not a member yet? Register   Sign In
DUPLICATE KEY UPDATE in the query builder
#1

I would like to execute the following SQL in the query builder.
Code:
INSERT INTO table1 (`id`, `total`) VALUES (123, 1) ON DUPLICATE KEY UPDATE total = total + 1;

We want to execute 1 if the id does not exist and the existing value + 1 if it exists.

I tried the code below, but it is not what I expected.
PHP Code:
$data = [
    'id' => 100,
    'total' => "todal + 1",
];

$builder $db->table('table1');
$builder->upsert($data); 

Generated queries
Code:
INSERT INTO `table1` (`id`, `total`) VALUES (100,'todal + 1') ON DUPLICATE KEY UPDATE `table1`.`id` = VALUES(`id`), `table1`.`total` = VALUES(`total`)


I was hoping for "upsert" to be available after version 4.3, but is that impossible?
https://www.codeigniter.com/user_guide/d...rting-data

Ultimately, I would like to use "upsertBatch".
Reply
#2

PHP Code:
$data = [
    'id' => 100,
    'total' => "todal + 1"// <-- this will not add 1 to total!
];

// but this will.

$total $total +1;

$data = [
    'id' => 100,
    'total' => $total,
]; 
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply
#3

Thank you for your answer.
I don't think you understood the intent of my question, so I will change my explanation.

I want to generate the following MySQL query using the query builder.
Code:
INSERT INTO table1 (`id`, `total`) VALUES (123, 1) ON DUPLICATE KEY UPDATE total = total + 1;

reference
https://dev.mysql.com/doc/refman/8.0/en/...icate.html

Can this be accomplished with Codeigniter's Query Builder?
https://www.codeigniter.com/user_guide/d...ery#upsert

Currently, we have no choice but to use the following method to achieve this situation.
PHP Code:
$data = [
    'id' => 100,
    'total' => 1,
];

$sql "INSERT INTO table1 (id, total) VALUES (?, ?) ON DUPLICATE KEY UPDATE total = total + ?";
$db->query($sql, [$data['id'], $data['total'],  $data['total']]); 
Reply
#4

This is probably the best solution
Reply




Theme © iAndrew 2016 - Forum software by © MyBB