在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:"[email protected]", 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:"[email protected]", 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 } }
-
效果圖