HasOne

Below is how you can define a HasOne relationship.

@Definition()
export class Product {
  @Id()
  id: ObjectId;
 
  @Property()
  name: string;
 
  @HasOne(() => FeatureImage, {
    to: 'productId',
    allowCreateWithin: true,
  })
  featureImage: Ref<FeatureImage>;
}
 
@Definition()
export class FeatureImage {
  @Id()
  id: ObjectId;
 
  @Property()
  url: string;
 
  @Property({ type: () => GraphQLObjectId })
  productId: ObjectId;
 
  @BelongsTo(() => Product, { from: 'productId' })
  product: Product;
}
💡

Ref is a type function imported from 'dryerjs', not using Ref will result in a ReferenceError

In the above example, we have defined a HasOne relationship between Product and FeatureImage. This means that a Product can have one FeatureImage. Because of that we have to define a storeId property on the FeatureImage class. This is the foreign key that will be used to identify which Product a FeatureImage belongs to.

Create API

mutation {
  createProduct(input: {
    name: "Awsome Product",
    featureImage: { url: "https://dryerjs.com/logo.png" }
  }) {
    id
    name
    featureImage {
      id
      url
    }
  }
}
💡

If you want to prevent the creation of a featureImage along with a product, you can set allowCreateWithin to false in the options or simply omit it.

Resolve fields

💡

To prevent the resolution of the featureImage field, set noPopulation to true.

@Definition()
export class Product {
  @HasOne(() => FeatureImage, {
    to: 'productId',
    noPopulation: true,
  })
  featureImage: Ref<FeatureImage>;
}

Ensure relationship

By default, you cannot remove a Product if it has a FeatureImage. To allow removal in this case, you can set skipRelationCheckOnRemove to true in the options.