-
Notifications
You must be signed in to change notification settings - Fork 0
Relations
Backend allows you to define nested relationships by defining a has and/or belongsTo value on on a field that contains the relationship.
Because relationships are resolved in the read method of the related type, has relations are converted to belongsTo relationships in the related type
Before proceeding, the reader should be familiar with graphql-factory definition syntax
A has relationship means that the field it is defined on contains a foreignKey value in the backend store but resolves to the full document.
There are two types of has relationships, a hasOne and hasMany. Both are configured by adding a has definition to the related field
-
hasManyrelationships are automatically determined by the fieldstype. If the field type is a list, then the relation is ahasMany -
hasOnerelationships are used if the field type is not a list
A belongsTo relationship is a bit more tricky. Like the has relationship the field it is defined on contains a foreignKey value. Since relationships are resolved by the nested type's read resolver, a belongsTo definition contains information on the source type, field, and primaryKey. During a query, the read resolver analyzes the defined relations and the resolver info to determine if it should resolve the relationship.
In the following example, the favoritePet field defines a hasOne relationship because it specifies a has property on a field with a non-list type. This means that the value in the backend for Person.favoritePet contains a string that identifies a Pet.id. The value can be null if nullable is not false
const Person = {
fields: {
id: {
type: 'String',
primary: true
},
name: {
type: 'String',
nullable: false
},
favoritePet: {
type: 'Pet'
has: {
foreignKey: 'id'
}
}
}
}
const Pet = {
fields: {
id: {
type: 'String',
primary: true
},
name: {
type: 'String',
nullable: false
}
}
}In the following example, the bookmarks field defines a hasMany relationship because its field type is a list of type Bookmark where the primaryKey of Bookmark is id. This means that the value in the backend for Person.bookmarks contains an array/list that identifies one or more Bookmark.id. The value can also be an empty array/list
const Person = {
fields: {
id: {
type: 'String',
primary: true
},
name: {
type: 'String',
nullable: false
},
bookmarks: {
type: ['Bookmark']
has: {
foreignKey: 'id'
}
}
}
}
const Bookmark = {
fields: {
id: {
type: 'String',
primary: true
},
name: {
type: 'String',
nullable: false
},
url: {
type: 'String',
nullable: false
}
}
}const Group = {
fields: {
id: {
type: 'String',
primary: true
},
name: {
type: 'String',
nullable: false
},
owner: {
type: 'Person'
}
}
}
const Person = {
fields: {
id: {
type: 'String',
primary: true
},
name: {
type: 'String',
nullable: false
},
group: {
type: 'String'
belongsTo: {
Group: {
owner: {
foreignKey: 'id'
}
}
}
}
}
}