onDuplicate()
Defines an ON DUPLICATE KEY UPDATE
clause for INSERT queries.
Useful for UPSERT operations where you want to update specific fields if a unique constraint is violated.
Signature:
public function onDuplicate(array $updateData): self
Example: Insert or update
// Insert user, or update email if username already exists
$data = [
'username' => 'alice',
'email' => 'alice@example.com'
];
$update = [
'email' => 'alice@example.com'
];
$db->onDuplicate($update);
$db->insert('test_users', $data);
Note: This method must be called before
insert()
or insertMulti()
. It does not affect insertBulk()
or replace()
.
Supports: Special placeholders like
[F]
(for internal usage), subquery objects, and methods like $db->now()
for dynamic timestamps.
Use Cases
- Perform upserts on unique constraints like
email
orusername
- Avoid duplicate entry errors by automatically updating fields
- Use dynamic values like
updated_at = NOW()
via'updated_at' => $db->now()