SQL Update

await db.update(users)
  .set({ name: 'Mr. Dan' })
  .where(eq(users.name, 'Dan'));

您传递给 update 的对象应该具有与数据库架构中列名匹配的键。 对象中忽略 undefined 的值:要将列设置为 null,请传递 null。 您可以将 SQL 作为值传递给更新对象,就像这样:

await db.update(users)
  .set({ updatedAt: sql`NOW()` })
  .where(eq(users.name, 'Dan'));

带返回值的更新

PostgreSQL
SQLite
MySQL

您可以在 PostgreSQL 和 SQLite 中更新一行并获取它回来:

const updatedUserId: { updatedId: number }[] = await db.update(users)
  .set({ name: 'Mr. Dan' })
  .where(eq(users.name, 'Dan'))
  .returning({ updatedId: users.id });

WITH 更新子句

💡

查看如何使用 WITH 语句与 selectinsertdelete

使用 with 子句可以帮助您通过将复杂的查询拆分为称为公用表表达式(CTEs)的较小子查询来简化复杂查询:

const averagePrice = db.$with('average_price').as(
        db.select({ value: sql`avg(${products.price})`.as('value') }).from(products)
);

const result = await db.with(averagePrice)
    .update(products)
    .set({
      cheap: true
    })
    .where(lt(products.price, sql`(select * from ${averagePrice})`))
    .returning({
      id: products.id
    });
with "average_price" as (select avg("price") as "value" from "products") 
update "products" set "cheap" = $1 
where "products"."price" < (select * from "average_price") 
returning "id"
Become a Gold Sponsor