一对多关系
一对多 (1-n) 关系指其中一侧可以关联另一侧零或多条记录的关系
注意
注意
一个列表字段,不标注
@relation必须填写 没有?带标注的关系字段包含(其关系标量) 要么都是选填 要么都是必填
表的关系
ts
model dept {
id Int @id @default(autoincrement())
name String @db.VarChar(50)
emp emp[]
}
model emp {
id Int @id @default(autoincrement())
name String @db.VarChar(50)
age Int?
job String? @db.VarChar(20)
salary Int?
entrydate DateTime? @db.Date
managerid Int?
dept_id Int?
dept dept? @relation(fields: [dept_id], references: [id])
}查询语法
注意
注意
include 不能和 select 同级别
最好使用 select 这样最省事.要是嵌套的话 里面再写一个 select
查询
ts
async onebymany() {
const result = await this.prismadbService.dept.findMany({
select: {
name: true,
emp: {
select: {
name: true,
},
},
},
});
return result;
}插入语法
场景说明
部门表 dept 是一(1),员工表 emp 是多(n)
一个部门可以有多个员工,比如"研发部"下面有"张三、李四、王五"三个员工
方式一:嵌套创建(推荐)
一次请求,同时创建部门和它下面的员工
ts
async insertOneByMany() {
const result = await this.prismadbService.dept.create({
data: {
name: '研发部', // 创建一个部门
emp: {
create: [
// 同时创建这个部门下的多个员工
{ name: '张三', age: 25, salary: 8000 },
{ name: '李四', age: 28, salary: 12000 },
{ name: '王五', age: 30, salary: 15000 },
],
},
},
});
return result;
}说明
create 里面再写 emp: { create: [...] } 就是嵌套创建
Prisma 会自动处理好外键 dept_id,不用我们手动填
方式二:连接已有数据(connect)
部门已经存在,现在要把一个已存在的员工挂到这个部门下面
ts
async insertConnect() {
const result = await this.prismadbService.emp.create({
data: {
name: '赵六',
age: 26,
salary: 10000,
dept: {
connect: {
id: 1, // 把这个员工连接到 id 为 1 的部门
},
},
},
});
return result;
}create 和 connect 的区别
create:员工和部门都不存在,一起新建connect:部门已经存在,只新建员工并关联过去
方式三:直接写外键(最简单)
如果知道部门的 id,也可以直接填外键字段 dept_id
ts
async insertByForeignKey() {
const result = await this.prismadbService.emp.create({
data: {
name: '孙七',
age: 24,
salary: 7000,
dept_id: 1, // 直接写部门 id
},
});
return result;
}注意
注意
嵌套创建时外键
dept_id不用自己写,Prisma 自动处理用
connect时,连接的部门必须真实存在,否则会报错批量插入员工到同一部门,可以用
createMany:
ts
async insertMany() {
const result = await this.prismadbService.emp.createMany({
data: [
{ name: '周八', age: 27, salary: 9000, dept_id: 1 },
{ name: '吴九', age: 29, salary: 11000, dept_id: 1 },
],
});
return result;
}注意:createMany 只能直接写外键,不支持嵌套 create