Как загрузить объект с его отношением ownTo в loopback 4 - PullRequest
0 голосов
/ 23 сентября 2019

Я новичок в loopback 4 и Nodejs.Я хочу загрузить сущность с именем Pratica, определяющую отношение BelongsTo, целью которого является другая сущность с именем Stato.

Я следовал этому учебнику в документации по loopback 4, но он объясняет, как это сделать с HasManyотношение.

Это схема, приводящая к созданию проводника API, сгенерированного Loopback для конечной точки "/ pratiche / {id}"

{
  "protocolloaci": 0,
  "codicepratica": "string",
  "stato": {
    "stato": 0,
    "descrizione": "string"
  }
}

Моя модель, репозиторий и класс контроллера в машинописи

pratica.model.ts

import { Entity, model, property, belongsTo } from '@loopback/repository';
import { Stato, StatoWithRelations } from './stato.model';

@model({ settings: { strict: false } })
export class Pratica extends Entity {

  other properties
  ...

  @belongsTo(() => Stato)
  stato: Stato;
  // Define well-known properties here

  // Indexer property to allow additional data
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  [prop: string]: any;

  constructor(data?: Partial<Pratica>) {
    super(data);
  }
}

export interface PraticaRelations {
  stato: StatoWithRelations;
}

export type PraticaWithRelations = Pratica & PraticaRelations;

stato.model.ts

@model({ settings: {} })
export class Stato extends Entity {
  @property({
    type: 'number',
    id: true,
    required: true,
    generated: false,
  })
  stato: number;

  @property({
    type: 'string',
    required: true,
  })
  descrizione: string;

  constructor(data?: Partial<Stato>) {
    super(data);
  }
}

export interface StatoRelations {
  // describe navigational properties here
}

export type StatoWithRelations = Stato & StatoRelations;

pratica.repository.ts

export class PraticaRepository extends DefaultCrudRepository<
  Pratica,
  typeof Pratica.prototype.protocolloaci,
  PraticaRelations
  > {

  public readonly stato: BelongsToAccessor<Stato, typeof Pratica.prototype.protocolloaci>;

  constructor(
    @inject('datasources.praticaDs') dataSource: PraticaDsDataSource, @repository.getter('StatoRepository') protected statoRepositoryGetter: Getter<StatoRepository>,
  ) {
    super(Pratica, dataSource);
    this.stato = this.createBelongsToAccessorFor('stato', statoRepositoryGetter);
  }

  async findById(
    id: typeof Pratica.prototype.id,
    filter?: Filter<Pratica>,
    options?: Options,
  ): Promise<PraticaWithRelations> {
    // Prevent juggler for applying "include" filter
    // Juggler is not aware of LB4 relations
    const include = filter && filter.include;
    filter = { ...filter, include: undefined };

    const result = await super.findById(id, filter, options);

    // poor-mans inclusion resolver, this should be handled by DefaultCrudRepo
    // and use `inq` operator to fetch related todos in fewer DB queries
    // this is a temporary implementation, please see
    // https://github.com/strongloop/loopback-next/issues/3195
    if (include && include.length && include[0].relation === 'stato') {
      result.stato = await this.stato(result.protocolloaci);
    }

    return result;
  }
}

методcontroller pratica.controller.ts

@get('/pratiche/{id}', {
    responses: {
      '200': {
        description: 'Pratica model instance',
        content: { 'application/json': { schema: getModelSchemaRef(Pratica, { includeRelations: true }) } },
      },
    },
  })
  async findById(@param.path.number('id') id: number): Promise<Pratica> {
    return this.praticaRepository.findById(id);
  }

Это то, что я получаю от проводника.Как вы можете видеть, свойство stato является числом в соответствии с определением базы данных свойства.Я ожидаю, что это сложный объект с идентификатором и описанием

{
  "protocolloaci": 243835076,
  "codicepratica": "C03301",
  "stato": 271
}

Спасибо.

...