在prisma(四)中是简单的CRUD
,那么今天我们深入研究下CRUD
,即集合之间的关联。
使用的集合
users、Post
先来看下users
集合中关联Post
集合。
datamodel
type User @db(name: "users") {
_id: ID! @id
age: Int
email: String
isUse: Boolean
name: String
post:Post@relation(link: INLINE) //关联post集合
}
type Post{
_id: ID! @id
author:String
}
定义好datamodel后运行prisma deploy
命令,这时候在generated
文件夹下面的prisma-schema.js
中会生成相应的方法,一起来看看吧:👇👇👇
prisma-schema.js
注意,这个文件会生成很多方法或类型,我大概挑几个使用的吧:
type Post {
_id: ID!
author: String
}
type User {
_id: ID!
age: Int
email: String
isUse: Boolean
name: String
post: Post
}
type Mutation {
createUser(data: UserCreateInput!): User!
}
input UserCreateInput {
_id: ID
age: Int
email: String
isUse: Boolean
name: String
post: PostCreateOneInput
}
input PostCreateOneInput {
create: PostCreateInput
connect: PostWhereUniqueInput
}
type Query {
users(where: UserWhereInput, orderBy: UserOrderByInput, skip: Int, after: String, before: String, first: Int, last: Int): [User]!
}
接下来我们去playground
中进行相关操作。
C
- 代码
mutation{ createUser( data:{ name:"Anna", age:20, email:"23", isUse:true, post:{ create:{ author:"Anna" } } } ){ _id, name, email, age, post{ _id, author } } }
- 效果图
R
- 代码
{ users{ _id, name, age, post{ _id, author } } }
- 效果
U
-
代码
mutation{ updateUser( where:{_id:"5e1ece7df0c1310007bb2dc2"} data:{ name:"Linda", age:20, email:"123@qq.com", isUse:true, post:{ update:{ author:"Linda" } } } ){ _id, name, age, email, isUse, post{ _id, author } } }
-
效果图
D
-
代码
mutation{ deleteUser( where:{_id:"5e1ece7df0c1310007bb2dc2"} ){ _id, name, email, isUse, age, post{ _id, author } } }
-
效果图
如何删除关联的Post
集合中的数据呢❓有待研究🤔🤔🤔
以上是users
集合中关联Post
,那如果这两个集合之间是双向关系呢❓该如何操作呢❓我们一起来看看吧👇👇👇
datamodel
type User @db(name: "users") {
_id: ID! @id
age: Int
email: String
isUse: Boolean
name: String
post:Post@relation(link: INLINE)
}
type Post{
_id: ID! @id
author:User //上面author是String类型,此处来关联User类型
name:String //多加一个书的作者字段
}
prisma-schema.js
在datamodel
中定义好字段后继续运行prisma deploy
来部署API,如下图(以createPost
为例):

接下来打开playground
来进行CRUD
👇👇👇
C
-
代码
createPost( data:{ name:"围城", author:{ create:{ name:"钱锺书", age:18, email:"12@qq.com", isUse:true } } } ){ _id, name, author{ _id, name, age, isUse, email } } }
-
效果图
R
-
代码
{ posts{ _id, author{ _id, name, age, email, isUse } name } }
-
效果图
U
可以修改集合中的任何内容,要修改的内容放在data
中,下面以修改作者的年龄为例:
-
代码
mutation{ updatePost( where:{_id:"5e2308daf0c131000719ff4c"} data:{ author:{ update:{ age:90 } } } ){ _id, author{ _id, name, age, email, isUse } name } }
-
效果图
D
-
代码
deletePost( where:{_id:"5e2308daf0c131000719ff4c"} ){ _id, name, author{ _id, name, age, email, isUse } }
-
效果图