BelongsTo
If you have not read the HasMany guide, please do so before continuing.
From the example on HasMany, you can add @BelongsTo
to define the Product
to Store
relationship.
@Definition()
export class Product {
@Id()
id: ObjectId;
@Property()
name: string;
@Property({ type: () => GraphQLObjectId })
storeId: ObjectId;
@BelongsTo(() => Store, { from: 'storeId' })
store: Store;
}
Resolve field
You will be able to resolve the store
field on the Product
type.
query {
product(id: "000000000000000000000000") {
id
name
store {
name
id
}
storeId
}
}
💡
To prevent resolving the store
field, set noPopulation
to true
.
@Definition()
export class Product {
@BelongsTo(() => Store, { from: 'storeId', noPopulation: true })
store: Store;
}
Ensure relationship
By default, you cannot create a Product
with a storeId
that does not exist. You can change this behavior by setting the skipExistenceCheck
option to true
.
@Definition()
export class Product {
@BelongsTo(() => Store, { from: 'storeId', skipExistenceCheck: true })
store: Store;
}