Relations
Resolve nested relations
Declare the relation in the table, register both types in the graph, and declare the relation field in the GraphQL schema:
class UserTable extends BaseTable {
readonly table = "user"
columns = this.setColumns(t => ({
id: t.identity().primaryKey(),
name: t.text(),
}))
relations = {
posts: this.hasMany(() => PostTable, {
columns: ["id"],
references: ["author_id"],
}),
}
}
class PostTable extends BaseTable {
readonly table = "post"
columns = this.setColumns(t => ({
id: t.identity().primaryKey(),
text: t.text(),
author_id: t.integer(),
}))
relations = {
author: this.belongsTo(() => UserTable, {
required: true,
columns: ["author_id"],
references: ["id"],
}),
}
}
const db = orchidORM(
{ databaseURL: process.env.DATABASE_URL },
{ user: UserTable, post: PostTable },
)
const graph = r.graph({
User: r.table(db.user),
Post: r.table(db.post),
})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 an Orchid ORM subquery 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
}
}
}A query can follow the same relations more than once:
query deep_nesting {
posts {
id
author {
name
posts {
id
author {
name
}
}
}
}
}Currently broken
With orchid-orm 1.78.63, Orchid ORM fails on queries that traverse the same relations more times than above, such as posts { author { posts { author { posts { id } } } } } (orchid-orm#939).
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.table(db.user, {
fields: {
id: true,
name: true,
articles: "posts",
},
}),
Post: r.table(db.post),
})To combine the new name with other options, pass the relation as tableField of r.relation:
articles: r.relation({ tableField: "posts", modify: query => query.order({ 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.table(db.user, {
fields: {
id: true,
name: true,
posts: r.relation({
modify: (query, { tree }) => {
return query.order({ id: tree.args.newest_first ? "DESC" : "ASC" })
},
}),
},
}),
Post: r.table(db.post),
})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.