Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drizzle ORM not support Insert Returning

I have a question while working with Drizzle ORM and MySQL.

Currently, Drizzle ORM does not provide insert returning function for MySQL. Check this link.

My website adds users to the database and issues JWT tokens when they sign up. Since the payload of the JWT must include the id of the newly added user, it is essential to know the id of the user that was just added.

In this case, how do I get the id which is an auto-incrementing integer for the record I added?


2 Answers

Drizzle ORM doesn't support the returning function for MySQL, but it does have a way of giving you the auto-incremented ID by using the insertId property

Example:

const userTable = await db.insert(user).values({ name: "Jorge"})


const walletTable = await db.insert(wallet).values({ userId: userTable.insertId)
like image 183
jorgemanc Avatar answered Jul 18 '26 04:07

jorgemanc


According to the Drizzle Docs

await db.insert(users).values({ name: "Dan" }).returning();

// partial return
await db.insert(users).values({ name: "Partial Dan" }).returning({ insertedId: users.id });

This will return an array of inserted rows. To get a single value, you could:

const newUser = await db.insert(users).values({ name: "Partial Dan" }).returning({ insertedId: users.id });

return newUser[0];

EDIT: This is for PostgreSQL and SQLite and is NOT SUPPORTED on MySQL. Apologies as I missed that earlier.

like image 42
chris Avatar answered Jul 18 '26 06:07

chris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!