Skip to content

Commit c703f1a

Browse files
committed
#23 v5'te (initphp/database@^5.0) raw query yolunu kullanmak hâlâ doğru pattern — REPLACE INTO standart SQL değil. Detaylı örnekler ve cross-driver eşdeğerleri (PostgreSQL ON CONFLICT, MySQL 8 ON DUPLICATE KEY UPDATE) için: docs/03-crud.md#replace-into--upsert
1 parent b324026 commit c703f1a

1 file changed

Lines changed: 54 additions & 0 deletions

File tree

‎docs/03-crud.md‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,60 @@ DB::where('id', 13)->delete('posts');
125125

126126
When working through a `Model` with `$useSoftDeletes = true`, this becomes a soft delete by default — pass `$purge = true` to bypass the soft-delete path. See [04 — Models](04-models.md).
127127

128+
## REPLACE INTO / UPSERT
129+
130+
The query builder has no native `REPLACE INTO` (or "upsert") method — the operation is not standard SQL and the exact spelling differs from one driver to the next. Reach for `DB::query()` with raw SQL when you need it; every driver-specific dialect goes through the same prepared-statement path.
131+
132+
### MySQL / MariaDB / SQLite — `REPLACE INTO`
133+
134+
```php
135+
DB::query(
136+
'REPLACE INTO items (id, name) VALUES (:id, :name)',
137+
[':id' => 1, ':name' => 'Alice']
138+
);
139+
```
140+
141+
`REPLACE INTO` deletes a conflicting row and inserts the new one — be aware that this fires `ON DELETE` triggers and reissues auto-increment IDs. SQLite supports the same syntax (and also accepts `INSERT OR REPLACE INTO` as a synonym).
142+
143+
### PostgreSQL — `INSERT ... ON CONFLICT`
144+
145+
```php
146+
DB::query(
147+
'INSERT INTO items (id, name) VALUES (:id, :name)
148+
ON CONFLICT (id) DO UPDATE SET name = EXCLUDED.name',
149+
[':id' => 1, ':name' => 'Alice']
150+
);
151+
```
152+
153+
`ON CONFLICT` is generally the better choice when it's available: no DELETE happens, triggers behave normally, and the conflict target is explicit.
154+
155+
### MySQL 8 — `INSERT ... ON DUPLICATE KEY UPDATE`
156+
157+
```php
158+
DB::query(
159+
'INSERT INTO items (id, name) VALUES (:id, :name)
160+
ON DUPLICATE KEY UPDATE name = VALUES(name)',
161+
[':id' => 1, ':name' => 'Alice']
162+
);
163+
```
164+
165+
Same intent as PostgreSQL's `ON CONFLICT` — preferred over `REPLACE INTO` for the same reasons.
166+
167+
### Batching upserts
168+
169+
`DB::query()` takes one statement at a time. If you need to upsert a batch, run them inside a transaction so the round-trips are amortised and you get atomicity for free:
170+
171+
```php
172+
DB::transaction(function ($db) use ($rows) {
173+
foreach ($rows as $row) {
174+
$db->query(
175+
'REPLACE INTO items (id, name) VALUES (:id, :name)',
176+
[':id' => $row['id'], ':name' => $row['name']]
177+
);
178+
}
179+
});
180+
```
181+
128182
## Raw SQL
129183

130184
When the query is faster to write by hand:

0 commit comments

Comments
 (0)