0

我正在使用 LoopBack 4 及其 mysql 连接器设置 api。所以我有一个模型飞机,它与飞行员有@hasMany 关系:

    class Plane extends Entity {
     @property({
      id: true,"dataPrecision": 10, "dataScale": 0, "nullable": "N" },
     })
     id: number;

     @property()
     name: string;

     @hasMany(() => Pilot, { keyTo: 'planeId' })
     pilots?: Array<Pilot>;

所以现在我想做的是创建一架飞机并在一个请求中添加它的飞行员。在我的飞机存储库中,我做了这样的事情:

class PlaneRepository extends DefaultCrudRepository<...> {
  planes;

  constructor(
    @inject('datasources') dataSource: any,
    @repository.getter('PilotRepository') getPilotRepository
  ) {
    this.planes = this.createHasManyRepositoryFactoryFor('planes', getIpilotRepository);
  }

我的控制器看起来像这样:

class PlaneController {
  @post('/project', {
    responses: {
      '200': {
        description: 'Plane model instance',
        content: { 'application/json': { schema: getModelSchemaRef(Project) }        
      },
    },
  })
  async create(
    @requestBody({
      content: {
        'application/json': {
          schema: getModelSchemaRef(Plane, { exclude: ['id'], includeRelations: true }),
        },
      },
    })
    plane: Omit<Plane, 'id'>,
  ): Promise<plane> {
    return this.planeRepository.create(plane);
  }
}

但是当我尝试用类似的东西调用我的路线时

{ name: 'Jet 27', pilots: [ { id: 0, name: Chuck Berry } ] }

我有一个 422 错误:

Plane实例无效。详细信息:pilots模型中未定义(值:未定义)。”

我不知道这是否是预期的行为,我必须承认我对关系的运作方式有点困惑,但如果是,那我该怎么做。

4

1 回答 1

0

从上面的示例中创建像您这样的模型时plane,它并不打算像pilots在 requestBody 中那样传递导航属性。甚至还有一个最近登陆的功能会拒绝无法处理的请求。

如果你真的想处理这样复杂的请求,例如将多个客户端请求保存到不同的端点,你可以直接在你的控制器类中实现这样的行为,但是你必须从planeRepository传递的对象中删除导航属性(因为这会抛出一个例外)。

示例(未测试):

  @post('/project', {
    responses: {
      '200': {
        description: 'Plane model instance',
        content: { 'application/json': { schema: getModelSchemaRef(Project) }        
      },
    },
  })
  async create(
    @requestBody({
      content: {
        'application/json': {
          schema: getModelSchemaRef(PlaneWithRelations, { exclude: ['id'] }),
        },
      },
    })
    plane: Omit<PlaneWithRelations, 'id'>,
  ): Promise<Plane> {
    const plane = await this.planeRepository.create({ name: plane.name });
    for (const pilot of planes.pilots) {
      await this.pilotRepository.create({ ...pilot, planeId: plane.id });
    }
    return plane;
  }

还应该可以对数据库事务中的更改进行分组

于 2019-12-05T00:17:03.617 回答