'Loopback4 hasMany not return the link array
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
?
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Tayyab Gulzar |