NextJS开发:Prisma数据库多表关联查询,使用include替代left join

Prisma中的多表关联查询实例

1、schema.prisma中定义模型

model Account {
  @@map("account")
  accountId         Int @id @default(autoincrement()) @map("account_id")
  nickName          String? @db.VarChar(32) @map("nick_name")
  pwd               String? @db.VarChar(128)
  mobile            String? @db.VarChar(11)
  email             String? @db.VarChar(20)
  createAt          DateTime @map("create_at")
  lastLoginAt       DateTime? @map("last_login_at")
  chapters          Chapter[]
}

model Chapter {
  @@map("d_chapter")
  chapterId         BigInt @id @default(autoincrement()) @map("chapter_id")
  account           Account @relation(fields: [accountId], references: [accountId])
  accountId         Int @map("account_id")
  ...
  createAt          DateTime @map("create_at")
  updateAt          DateTime? @map("update_at")
  content           ChapterContent?
}

2、查询操作

let chapters = await Db.share().chapter.findMany({
  orderBy: {
    chapterId: "desc"
  },
  skip: offset,
  take: limit,
  include: {
    account: true
  }
})

3、查看日志中生成sql

prisma:query SELECT `nextbbsdb`.`d_chapter`.`chapter_id`, `nextbbsdb`.`d_chapter`.`account_id`, `nextbbsdb`.`d_chapter`.`chapter_type`, `nextbbsdb`.`d_chapter`.`doc_id`, `nextbbsdb`.`d_chapter`.`topic_id`, `nextbbsdb`.`d_chapter`.`pid`, `nextbbsdb`.`d_chapter`.`state`, `nextbbsdb`.`d_chapter`.`type`, `nextbbsdb`.`d_chapter`.`chapter_name`, `nextbbsdb`.`d_chapter`.`thumb`, `nextbbsdb`.`d_chapter`.`file_format`, `nextbbsdb`.`d_chapter`.`keywords`, `nextbbsdb`.`d_chapter`.`intro`, `nextbbsdb`.`d_chapter`.`browse_num`, `nextbbsdb`.`d_chapter`.`reply_num`, `nextbbsdb`.`d_chapter`.`order_no`, `nextbbsdb`.`d_chapter`.`create_at`, `nextbbsdb`.`d_chapter`.`update_at`, `nextbbsdb`.`d_chapter`.`audit_at`, `nextbbsdb`.`d_chapter`.`is_del` FROM `nextbbsdb`.`d_chapter` WHERE `nextbbsdb`.`d_chapter`.`state` = ? ORDER BY `nextbbsdb`.`d_chapter`.`chapter_id` DESC LIMIT ? OFFSET ?
prisma:query SELECT `nextbbsdb`.`account`.`account_id`, `nextbbsdb`.`account`.`type`, `nextbbsdb`.`account`.`nick_name`, `nextbbsdb`.`account`.`pwd`, `nextbbsdb`.`account`.`mobile`, `nextbbsdb`.`account`.`email`, `nextbbsdb`.`account`.`create_at`, `nextbbsdb`.`account`.`last_login_at` FROM `nextbbsdb`.`account` WHERE `nextbbsdb`.`account`.`account_id` IN (?)

通过sql日志可以看出,Prisma是通过两条sql完成的查询,先查出chapter列表,在使用chapter中的主键集合,使用In查询的account,之后再组合数据进行结果返回。

4、如果想要直接使用left join查询,只能使用prisma提供的原始数据库访问方法了

const rows = await Db.share().$queryRaw`SELECT a.*,b.nick_name FROM d_chapter a left join account b on a.account_id=b.account_id`
  • 10
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ArslanRobot

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值