我正在尝试使用Graphcool为我们的产品设计后端.我们已经拥有该产品的域模型.
我面临的问题是非标量属性,我被迫使用@relation(太双向关系).
帮我设计以下案例
# projectId: cj4dsyc7ur8cc0142s3hesy1r
# version: 2
type File implements Node {
contentType: String!
createdAt: DateTime!
id: ID! @isUnique
name: String!
secret: String! @isUnique
size: Int!
updatedAt: DateTime!
url: String! @isUnique
}
type User implements Node {
createdAt: DateTime!
email: String @isUnique
id: ID! @isUnique
password: String
updatedAt: DateTime!
}
type Record implements Node {
createdAt: DateTime!
id: ID! @isUnique
name: String!
description: String!
createdBy: User!
modifiedBy: User!
}
Run Code Online (Sandbox Code Playgroud)
为此,我得到了错误
Errors
createdBy: The relation field `createdBy` must specify a `@relation` directive: `@relation(name: "MyRelation")`
modifiedBy: The relation field `modifiedBy` must specify a `@relation` directive: `@relation(name: "MyRelation")`
Run Code Online (Sandbox Code Playgroud)
然后,当我尝试添加关系时,我被迫执行以下操作
# projectId: cj4dsyc7ur8cc0142s3hesy1r
# version: 2
type File implements Node {
contentType: String!
createdAt: DateTime!
id: ID! @isUnique
name: String!
secret: String! @isUnique
size: Int!
updatedAt: DateTime!
url: String! @isUnique
}
type User implements Node {
createdAt: DateTime!
email: String @isUnique
id: ID! @isUnique
password: String
updatedAt: DateTime!
}
type Record implements Node {
createdAt: DateTime!
id: ID! @isUnique
name: String!
description: String!
createdBy: User! @relation(name: "createdBy")
modifiedBy: User! @relation(name: "modifiedBy")
}
Run Code Online (Sandbox Code Playgroud)
这会导致以下错误
Errors
createdBy: A relation directive with a name must appear exactly 2 times.
modifiedBy: A relation directive with a name must appear exactly 2 times.
Run Code Online (Sandbox Code Playgroud)
我理解每个非标量的传出graphcool都希望建立双向关系.但是考虑一下modifyBy和createdBy(User)的用例,我不能为我添加的每个实体的User对象建立关系.
在GraphCool上执行此操作的更好方法是什么?
另外,为什么GraphCool提出了这个限制,GraphQL没有规定这个限制?
干杯罗希特
感谢您使用Graphcool!
首先要做的事情.正如您所指出的,当您想要连接类型时,Graphcool会强制执行双向关系.在某些情况下,您事先知道您只想在一个方向上查询数据,因此您必须创建双向关系似乎不直观.
原因是Graphcool权限系统允许您根据数据结构简洁地指定权限规则.在您的情况下,您可能希望指定只允许帖子的创建者删除记录.
在实践中,事实证明,在实施权限规则时,通常最终需要反向关系.实现双向关系使整个编程模型更易于理解,并使您能够轻松实现权限规则.
对于您的模式,解决方案是扩展User类型,如下所示:
type User implements Node {
createdAt: DateTime!
email: String @isUnique
id: ID! @isUnique
password: String
updatedAt: DateTime!
createdRecords: [Record!]! @relation(name: "CreatedBy")
modifiedRecords: [Record!]! @relation(name: "UpdatedBy")
}
Run Code Online (Sandbox Code Playgroud)
(请注意,关系名称必须以大写字母开头)
希望有所帮助:-)