簡體   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