Give me an example how to add element to array with drizzle-orm during update
- User
Give me an example how to add element to array with drizzle-orm during update
Assistant
Here's how to add an element to an array field using Drizzle ORM during an update:
import { db } from './db'; import { users } from './schema'; import { eq, sql } from 'drizzle-orm'; // Method 1: Using SQL array_append function (PostgreSQL) await db .update(users) .set({ tags: sql`array_append(${users.tags}, ${newTag})` }) .where(eq(users.id, userId)); // Method 2: Using spread operator (fetch current, then update) const user = await db .select({ tags: users.tags }) .from(users) .where(eq(users.id, userId)) .limit(1); if (user[0]) { await db .update(users) .set({ tags: [...(user[0].tags || []), newTag] }) .where(eq(users.id, userId)); } // Method 3: Using PostgreSQL array concatenation await db .update(users) .set({ tags: sql`${users.tags} || ${[newTag]}` }) .where(eq(users.id, userId));
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.