Relations
Resolve nested relations
Declare the relation in relationMappings, register both types in the graph, and declare the relation field in the GraphQL schema:
class UserModel extends Model {
static tableName = "user"
static get relationMappings() {
return {
posts: {
relation: Model.HasManyRelation,
modelClass: PostModel,
join: { from: "user.id", to: "post.author_id" },
},
}
}
}
class PostModel extends Model {
static tableName = "post"
static get relationMappings() {
return {
author: {
relation: Model.BelongsToOneRelation,
modelClass: UserModel,
join: { from: "post.author_id", to: "user.id" },
},
}
}
}
const graph = r.graph({
User: r.model(UserModel),
Post: r.model(PostModel),
})type User {
id: Int!
name: String!
posts: [Post!]!
}
type Post {
id: Int!
text: String!
author: User!
}
type Query {
posts: [Post!]!
user(id: Int!): User
}The graph loads a relation with withGraphFetched when the client selects its field, and resolves the related objects with the resolver of their type:
query posts_with_author {
posts {
id
text
author {
name
}
}
}
query user_with_posts($id: Int!) {
user(id: $id) {
name
posts {
id
text
}
}
}Relations resolve at any depth, including the same relations again:
query deep_nesting {
posts {
id
author {
name
posts {
id
author {
name
}
}
}
}
}Many-to-many relations resolve the same way.
Rename a relation field
When the GraphQL field has a different name than the relation, map it to the relation in fields:
const graph = r.graph({
User: r.model(UserModel, {
fields: {
id: true,
name: true,
articles: "posts",
},
}),
Post: r.model(PostModel),
})To combine the new name with other options, pass the relation as tableField of r.relation:
articles: r.relation({ tableField: "posts", modify: query => query.orderBy("id", "desc") })See Fields for which other fields a type with fields resolves.
Modify the related rows
To order or restrict the related rows, such as by the arguments of the relation field, pass modify to r.relation:
type User {
id: Int!
name: String!
posts(newest_first: Boolean): [Post!]!
}const graph = r.graph({
User: r.model(UserModel, {
fields: {
id: true,
name: true,
posts: r.relation({
modify: (query, { tree }) => {
return query.orderBy("id", tree.args.newest_first ? "desc" : "asc")
},
}),
},
}),
Post: r.model(PostModel),
})tree.args holds the arguments of the relation field.
To post-process the loaded related value, pass transform(value, instance, context) to r.relation, as for r.field.
Currently broken
r.relation never calls transform.