0

I'm trying to query a SQL Server database of related tables and return the data. Something like a person, address, and order table all connected by the personId. How exactly would I retrieve this data using the models?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
rzulu
  • 11
  • 2

1 Answers1

1

The TodoList example is a demo for the relation traverse between models. See repository https://github.com/strongloop/loopback-next/tree/master/examples/todo-list.

And tutorial https://loopback.io/doc/en/lb4/todo-list-tutorial.html

In the example, two relations are established: model TodoList hasMany Todo and Todo belongsTo TodoList.

To query a related model's data, first define the relation property todos in the todo-list repository:

export class TodoListRepository extends DefaultCrudRepository<
  TodoList,
  typeof TodoList.prototype.id
> {
  public readonly todos: HasManyRepositoryFactory<
    Todo,
    typeof TodoList.prototype.id
  >;

  constructor(
    @inject('datasources.db') dataSource: juggler.DataSource,
    @repository.getter(TodoRepository)
    protected todoRepositoryGetter: Getter<TodoRepository>,
  ) {
    super(TodoList, dataSource);
    this.todos = this._createHasManyRepositoryFactoryFor(
      'todos',
      todoRepositoryGetter,
    );
  }
}

Then you can call this.todos(todoListId).find(filter) to query the todo model instances with foreignKey equal to that todoListId.

See how the relation api get called in the controller function as an example: https://github.com/strongloop/loopback-next/blob/master/examples/todo-list/src/controllers/todo-list-todo.controller.ts#L61

Janny Hou
  • 121
  • 3