繁体   English   中英

Prisma (ORM) - 获取插入行的索引值

[英]Prisma (ORM) - get the index value of inserted row

我正在尝试使用 Prisma (ORM) 来管理我的 MySQL 数据库。

当我直接使用 MySQL 时,我可以在插入命令后运行mysql_insert_id()以获取我刚刚插入的auto_increment索引值。

我怎样才能在 Prisma 中实现这一点? insert的返回值是受影响的行,而不是索引。

编辑

如果您使用prisma.create()它会返回带有新 ID 的 object。

但是如果你使用prisma.createMany()它只返回受影响的行数???!

有人愿意解释这背后的设计吗?

您需要使用原始查询来执行返回索引值的插入语句。

从文档中:

使用$queryRaw返回实际记录。

使用$executeRaw返回受影响的行数

所以你需要使用 queryRaw 方法。

你可以这样使用:

const now = new Date();
const createdRecord = await this.prisma.post.create({
      data: {
        title: input.title!,
        content: input.content!,
        created_at: now,
        updated_at: now
      }
    })

// now you can access id of created record by createdRecord.id
const id = createdRecord.id
// ...whatever you want with id

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM