How to get count of child records in hasMany relationship #7345
-
Currently I'm using the loopback3, and I'm planing to migrate my project into Loopback4. In my existing project I have created the relational API's using hasMany relationship. In loopback3 I'm able to get the count of child table once I pass the ID of parent table record(and also able to filter the count by where condition). Scenario: Tenant has many users. when I created hasMany relationship in loopback3, it provides me the E.x. But when I created hasMany relationship in Loopback4 I'm not getting API like this in my OpenAPI swagger(in tenant-user controller). Is there any workaround for this? OR is there any way to achieve this scenario in Loopback4? I'm using MySQL as my datasource. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 4 replies
-
Indeed that /count path is not created by default. But you can add it easily as follows: I will take the Also the count method from the repository receives a Where parameter, so we need to force the parent ID, so it behaves similar to other Step 1: import { Count, CountSchema, Filter, repository,Where,WhereBuilder } from '@loopback/repository';
import { TodoListRepository, TodoRepository } from '../repositories'; Step 2: @repository(TodoRepository)
protected todoRepository: TodoRepository Step 3: @get('/todo-lists/{id}/todos/count', {
responses: {
'200': {
description: 'Todo-list todo model count',
content: { 'application/json': { schema: CountSchema } },
},
},
})
async todoListTodoCount(
@param.path.number('id') id: number,
@param.where(Todo) where?: Where<Todo>,
): Promise<Count> {
const imposedWhereByTodoList = { todoListId: id };
if (where) {
where = new WhereBuilder(where).and(imposedWhereByTodoList).build();
} else {
where = new WhereBuilder(imposedWhereByTodoList).build();
}
return this.todoRepository.count(where);
} Additionally/Optionally and not related to the question in this discussion, if someone is trying to run at this moment the Add the todo repository: In the first Now in the last line change this line from And you will have it running without any error. |
Beta Was this translation helpful? Give feedback.
@HarshalNathe ,
Indeed that /count path is not created by default. But you can add it easily as follows: I will take the
todo-list
example as the basis for my explanation. The key part here is that thecount
method resides in the child repository. The controller that contains the relationship istodo-list-todo.controller.ts
so we need to import the repository of the child first, since the constrained relation repository does not have this method available for now.Also the count method from the repository receives a Where parameter, so we need to force the parent ID, so it behaves similar to other
/count
in regular controllers.Step 1:
Import the repository of the child in the relationshi…