简体   繁体   中英

Loopback 4: Join 2 related models

I am building a project were I have a list of jobs were each job belongs to a company.

REST controller called Job (just to make it simple) it has 2 methods:

  • @get('/jobs')
  • @get('/jobs/{id}')

For the case of @get('/jobs/{id}') I found a not perfect solution:

@get('/jobs/{id}', {
    responses: {
      '200': {
        description: 'Job model instance',
        content: {'application/json': {schema: {'x-ts-type': Job}}},
      },
    },
  })
  async findById(@param.path.number('id') id: number): Promise<Job> {
    const job: Job = await this.jobRepository.findById(id);
    const company: Company = await this.jobRepository.company(job.company_id);

    job.company = company;

    return job;
  }

I added a property company were I assigned the company.

But for @get('/jobs') it is not so easy, to apply similar approach I would have to loop all results to add company, but this approach it is not efficient.

Any ideas?

According to forums, Loopback is not able to do joins yet. It is scheduled for next 3 months though, meanwhile I solved doing:

@get('/jobs', {
    responses: {
      '200': {
        description: 'Array of Job model instances',
        content: {
          'application/json': {
            schema: {type: 'array', items: {'x-ts-type': Job}},
          },
        },
      },
    },
  })
  async find(
    @param.query.object('filter', getFilterSchemaFor(Job)) filter?: Filter,
  ): Promise<{jobs: Job[]; count: number}> {
    const jobs = await this.jobRepository.find(filter);

    await Promise.all(
      jobs.map(
        async (job): Promise<Job> => {
          let company = await this.jobRepository.company(job.company_id);
          return (job.company = company);
        },
      ),
    );

    const count = await this.jobRepository.count();

    return {jobs, ...count};
  }

If you have suggestions to improve code, let me know.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM