0

I just try to use the hasMany relationship according to the loopback4 documentation .but it's not working as expected.

My Bus Model =>

export class Bus extends Entity {
  @property({
    type: 'number',
    id: true,
    generated: true,
  })
  id?: number;

  @hasMany(() => BusStation, {keyTo: 'busId'})
  stations?: BusStation[];

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

export interface BusRelations {
  // describe navigational properties here
}

export type BusWithRelations = Bus & BusRelations ;

Bus Station Model =>

export class BusStation extends Entity {
  @property({
    type: 'number',
    id: true,
    generated: true,
  })
  id?: number;

  @property({
     type: 'number',
  })
  busId: number;

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

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

export interface BusStationRelations {
  // describe navigational properties here
}

export type BusStationWithRelations = BusStation & BusStationRelations;

Bus Repository =>

export class BusRepository extends DefaultCrudRepository<
  Bus,
  typeof Bus.prototype.id,
  BusRelations
> {
  public stations: HasManyRepositoryFactory<
    BusStation,
    typeof Bus.prototype.id
  >;

  constructor(
    @inject('datasources') dataSource: MyDataSource,
    @repository.getter('BusStationRepository')
    busStationRepositoryGetter: Getter<BusStationRepository>,
  ) {
    super(Bus, dataSource);
    this.stations = this.createHasManyRepositoryFactoryFor(
      'stations',
      busStationnRepositoryGetter,
    );
  }
}

My Expected Get Response of Bus =>

{
" id":1,
"stations":[
    {
        "id":1,
        "busId":1,
        "name":"Station 1"
    }
]
}

I did the exactly same with the documentation but why I can't get the response as I expected. Please May I know what I am missing?

I saw that some solution is to create another controller to connect these two models. Is it the only way? if yes, what is the reason for the hasMany?

1 Answer 1

0

in repository you have to include inclusion resolver under

this.stations = this.createHasManyRepositoryFactoryFor('stations',busStationnRepositoryGetter,);

like this

this.registerInclusionResolver('stations', this.stations.inclusionResolver);

on the other hand, you can use relation generator to avoid all this stuff.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.