Drizzle | 여러 행에 대해 각기 다른 값으로 업데이트하기
PostgreSQL
MySQL
SQLite
This guide assumes familiarity with:
한 번의 요청으로 여러 행에 대해 각기 다른 값으로 업데이트하려면 sql
연산자와 case
문, 그리고 .update().set()
메서드를 사용할 수 있습니다. 아래 예제를 참고하세요:
import { SQL, inArray, sql } from 'drizzle-orm';
import { users } from './schema';
const db = drizzle(...);
const inputs = [
{
id: 1,
city: 'New York',
},
{
id: 2,
city: 'Los Angeles',
},
{
id: 3,
city: 'Chicago',
},
];
// inputs 배열이 비어 있지 않은지 확인해야 합니다
if (inputs.length === 0) {
return;
}
const sqlChunks: SQL[] = [];
const ids: number[] = [];
sqlChunks.push(sql`(case`);
for (const input of inputs) {
sqlChunks.push(sql`when ${users.id} = ${input.id} then ${input.city}`);
ids.push(input.id);
}
sqlChunks.push(sql`end)`);
const finalSql: SQL = sql.join(sqlChunks, sql.raw(' '));
await db.update(users).set({ city: finalSql }).where(inArray(users.id, ids));
update users set "city" =
(case when id = 1 then 'New York' when id = 2 then 'Los Angeles' when id = 3 then 'Chicago' end)
where id in (1, 2, 3)