2

https://loopback.io/doc/en/lb4/HasMany-relation.html

我按照这些步骤操作,然后尝试获取数据,include但我得到了 500。

500 Error: Invalid "filter.include" entries: {"relation":"ranks"}

我想要的是获得具有相关等级的游戏对象。

等级模型

import { Entity, model, property, belongsTo } from '@loopback/repository';
import { Game, GameWithRelations } from './game.model';

@model({ settings: { strict: 'filter' } })
export class Rank extends Entity {
  @property({
    type: 'string',
    id: true,
  })
  id?: string;

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

  @property({
    type: 'string',
  })
  shortName?: string;

  @property({
    type: 'string',
  })
  avatar?: string;

  @belongsTo(() => Game)
  gameId: string;

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

export interface RankRelations {
  game?: GameWithRelations;
}

export type RankWithRelations = Rank & RankRelations;

游戏模型

import { Entity, model, property, embedsMany, hasMany } from '@loopback/repository';
import { Rank, RankWithRelations } from './rank.model';
import { HasMany } from 'loopback-datasource-juggler';

@model({ settings: { strict: 'filter' } })
export class Game extends Entity {
  @property({
    type: 'string',
    id: true,
  })
  id?: string;

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

  @property({
    type: 'string',
  })
  shortName?: string;

  @property({
    type: 'string',
  })
  avatar?: string;

  @hasMany<Rank>(() => Rank, { keyTo: 'gameId' })
  ranks?: Rank[];

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

export interface GameRelations {
}

export type GameWithRelations = Game & GameRelations;

游戏控制器

// in this method
// 500 Error: Invalid "filter.include" entries: {"relation":"ranks"}

 @get('/games/{id}')
  async findById(@param.path.string('id') id: string): Promise<Game> {
    return await this.gameRepository.findById(id, { include: [{ relation: 'ranks' }] });
  }
4

1 回答 1

9

请使用 运行您的应用程序DEBUG=loopback:repository:relation-helpers,这样您将收到一条调试消息,说明filter.include输入被拒绝的原因。

您可以在此处找到构建错误消息的代码:

https://github.com/strongloop/loopback-next/blob/97ba7893e253bfc2967ac08e408b211c9b9b7f40/packages/repository/src/relations/relation.helpers.ts#L96-L100

最可能的原因:您GameRepository没有为ranks关系注册任何 InclusionResolver。

请参阅我们的todo-list示例以了解如何注册包含解析器。来自https://github.com/strongloop/loopback-next/blob/97ba7893e253bfc2967ac08e408b211c9b9b7f40/examples/todo-list/src/repositories/todo-list.repository.ts#L41-L46的交叉发布:

this.todos = this.createHasManyRepositoryFactoryFor(
  'todos',
  todoRepositoryGetter,
);


this.registerInclusionResolver('todos', this.todos.inclusionResolver);
于 2019-10-04T14:48:13.560 回答