This relation best works with databases that support foreign keyconstraints (SQL).Using this relation with NoSQL databases will result in unexpected behavior,such as the ability to create a relation with a model that does not exist. We are to better handle this. It is fine to use this relation with NoSQL databases for purposes such as navigatingrelated models, where the referential integrity is not critical.

A relation denotes a many-to-one connection of a model to anothermodel through referential integrity. The referential integrity is enforced by aforeign key constraint on the source model which usually references a primarykey on the target model. This relation indicates that each instance of thedeclaring or source model belongs to exactly one instance of the target model.For example, in an application with customers and orders, an order alwaysbelongs to exactly one customer as illustrated in the diagram below.

The diagram shows the declaring (source) model Order has propertycustomerId as the foreign key to reference the target model Customer’sprimary key id.

To add a belongsTo relation to your LoopBack application and expose itsrelated routes, you need to perform the following steps:

  • Add a property to your source model to define the foreign key.
  • Modify the source model repository class to provide an accessor function forobtaining the target model instance.
  • Call the accessor function in your controller methods.

/src/models/order.model.ts

The definition of the belongsTo relation is inferred by using the @belongsTodecorator. The decorator takes in a function resolving the target model classconstructor and designates the relation type. It also calls property() toensure that the decorated property is correctly defined.

A usage of the decorator with a custom primary key of the target model for theabove example is as follows:

  1. class Order extends Entity {
  2. // constructor, properties, etc.
  3. @belongsTo(() => Customer, {keyTo: 'pk'})
  4. customerId: number;
  5. }
  6. export interface OrderRelations {
  7. customer?: CustomerWithRelations;
  8. }

The configuration and resolution of a belongsTo relation takes place at therepository level. Once belongsTo relation is defined on the source model, thenthere are a couple of steps involved to configure it and use it. On the sourcerepository, the following are required:

  • In the constructor of your source repository class, useDependency Injection to receive a getter functionfor obtaining an instance of the target repository. Note: We need a getterfunction, accepting a string repository name instead of a repositoryconstructor, or a repository instance, in order to break a cyclic dependencybetween a repository with a belongsTo relation and a repository with thematching hasMany relation.
  • Declare a property with the factory function typeBelongsToAccessor<targetModel, typeof sourceModel.prototype.id> on thesource repository class.
  • call the createBelongsToAccessorFor function in the constructor of thesource repository class with the relation name (decorated relation property onthe source model) and target repository instance and assign it the propertymentioned above.The following code snippet shows how it would look like:

/src/repositories/order.repository.ts

The same pattern used for ordinary repositories to expose their CRUD APIs viacontroller methods is employed for belongsTo relation too. Once the belongsTorelation has been defined and configured, a new controller method can expose theaccessor API as a new endpoint.

src/controllers/order.controller.ts

  1. import {repository} from '@loopback/repository';
  2. import {Customer, Order} from '../models/';
  3. import {OrderRepository} from '../repositories/';
  4. export class OrderController {
  5. constructor(
  6. @repository(OrderRepository) protected orderRepository: OrderRepository,
  7. ) {}
  8. // (skipping regular CRUD methods for Order)
  9. @get('/orders/{id}/customer')
  10. async getCustomer(
  11. @param.path.number('id') orderId: typeof Order.prototype.id,
  12. ): Promise<Customer> {
  13. return this.orderRepository.customer(orderId);
  14. }
  15. }

In LoopBack 3, the REST APIs for relations were exposed using static methodswith the name following the pattern {methodName}{relationName} (e.g.Order.get__customer). While we recommend to create a new controller for eachhasMany relation in LoopBack 4, we also think it’s best to use the main CRUDcontroller as the place where to explose belongsTo API.

Given an e-commerce system has many Category, each Category may have severalsub-categories, and may belong to 1 parent-category.

The CategoryRepository must be declared like below

  1. Category,
  2. typeof Category.prototype.id,
  3. > {
  4. public readonly parent: BelongsToAccessor<
  5. Category,
  6. typeof Category.prototype.id
  7. >;
  8. public readonly categories: HasManyRepositoryFactory<
  9. Category,
  10. typeof Category.prototype.id
  11. >;
  12. constructor(@inject('datasources.db') dataSource: DbDataSource) {
  13. super(Category, dataSource);
  14. this.categories = this.createHasManyRepositoryFactoryFor(
  15. 'categories',
  16. Getter.fromValue(this),
  17. );
  18. this.parent = this.createBelongsToAccessorFor(
  19. 'parent',
  20. Getter.fromValue(this),
  21. ); // for recursive relationship