1

我正在尝试使用 loopback4 belongsTo 关系,但我得到相同的错误“TypeError:无法读取未定义的属性'目标'”

源模型

每个房间都应该有一个类型

export class Rooms extends Entity {
  @property({
    type: 'string',
    id: true,
  })
  _id: string;

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

// relation ###
  @belongsTo(() => RoomsTypes)
  roomsTypesId: string;



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

目标模型

房间类型模型

@model({settings: {strict: false}})
export class RoomsTypes extends Entity {
  @property({
    type: 'string',
    id: true,
  })
  _id: string;

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

  @property({
    type: 'number',
    required: true,
  })
  numOfPeople: number;

  @property({
    type: 'array',
    itemType: 'string',
    required: true,
  })
  features: string[];


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

源存储库

我认为错误就在这里

import {
  DefaultCrudRepository,
  juggler,
  repository,
  BelongsToAccessor,
} from '@loopback/repository';
import { Rooms, RoomsRelations, RoomsTypes, RoomsTypesRelations} from '../models';
import {inject, Getter} from '@loopback/core';

import { RoomsTypesRepository } from './rooms-types.repository';

export class RoomsRepository extends DefaultCrudRepository<
  Rooms,
  typeof Rooms.prototype._id,
  RoomsRelations
> {
  public readonly roomTypes: BelongsToAccessor<
  RoomsTypes,
    typeof Rooms.prototype._id
  >;
  constructor(
    @inject('datasources.db')  protected DbDataSource: juggler.DataSource,
    @repository.getter('RoomsTypesRepository')
    RoomsTypesRepositoryGetter: Getter<RoomsTypesRepository>,
  ) {

    super(Rooms, DbDataSource);
    this.roomTypes = this.createBelongsToAccessorFor(
      'roomsTypesId',
      RoomsTypesRepositoryGetter,
    );
  }
}

我得到同样的错误“TypeError:无法读取未定义的属性'目标'”

4

1 回答 1

1

创建时,createBelongsToAccessorFor您需要指定关系名称,而不是关系 id:

this.roomTypes = this.createBelongsToAccessorFor('roomsTypesId', RoomsTypesRepositoryGetter);

应该

this.roomTypes = this.createBelongsToAccessorFor('roomTypes', RoomsTypesRepositoryGetter);

另外应该提到的是,环回对用于关系的属性的命名有一些假设。例如ID,关系的 由ModelName+构成Id。这也用于查找目标模型。

如果需要不同的命名,则需要在关系定义中指定keyTo或。keyFrom

官方文档最近更新了详细描述和@belongsTo关系示例:

@belongsTo 装饰器接受三个参数:

  • 目标模型类(必填)
  • 关系定义(可选)——具有三个属性,keyFrom、keyTo、name
    • keyFrom是“源”模型上外键的属性名称。它始终设置为修饰的属性名称(在给定的示例中,它是 Order 模型上的“customerId”属性)。
    • keyTo是“目标”模型上的外键的属性名称,它通常是“目标”模型的主键。keyTo 属性默认为目标模型上的 id 属性(在给定的示例中,客户上的“id”属性)。
    • name是存储库中定义的关系的名称。关系名称在存储库构造函数中用于定义 BelongsToAccessor 并使用包含解析器将其映射到关系。
  • property definition(可选)- 隐式创建一个属性装饰器。定义中的 name 属性可用于自定义数据源列名称。
于 2019-12-04T22:59:28.243 回答