【问题标题】:Loopback 4: Sending related dataLoopback 4:发送相关数据
【发布时间】:2019-03-28 01:20:02
【问题描述】:

我有一个表格,我可以用一个或多个地址注册用户。为了简化事情,我发送到环回:

{
  "id": 0,
  "name": "User Name",
  "addresses": [
    {
      "street": "xx",
      "city": "xx",
      "country": "xx"
    },
    {
      "street": "yy",
      "city": "yy",
      "country": "yy"
    }
  ]
}

在我定义的用户模型上(我也有一个地址模型):

export class User extends Entity {
  @property({
    type: 'number',
    id: true,
    required: true,
  })
  id: number;

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

 @hasMany(() => Address, {keyTo: ‘user_id’})
  Addresses: Array<Address>;
}

也在我定义的 UserRepository 中:

this.addresses = this.createHasManyRepositoryFactoryFor(
      'addresses',
      AddressRepositoryGetter,
    );

当我发布 json 时,loopback 会抛出以下错误:

{
  "error": {
    "statusCode": 422,
    "name": "ValidationError",
    "message": "The `user` instance is not valid. Details: `addresses` is not defined in the model (value: undefined).",
    "details": {
      "context": "user",
      "codes": {
        "addresses": [
          "unknown-property"
        ]
      },
      "messages": {
        "addresses": [
          "is not defined in the model"
        ]
      }
    }
  }
}

我的猜测是“地址”关系不被视为模型的属性。我该如何解决这个问题?我知道我可以选择单独请求保存地址,但我想避免这种情况。

【问题讨论】:

    标签: typescript loopbackjs v4l2loopback


    【解决方案1】:

    这个错误实际上是由datasource juggler抛出的,它是用于连接数据库的底层连接器库。似乎地址列未在 User 表中定义您的数据库。请检查一下。

    【讨论】:

    • 谢谢,是的,就是这样。如何在同一个请求中发送相关数据?地址是一个数组,将在地址模型中处理
    • 与您发送的方式相同。您只需要确保数据库具有此列。然而,杂耍者有时会表现得很奇怪。因此,在这种情况下,我更喜欢在控制器中单独处理相关数据。相关数据在同一个请求中按原样发送,但在控制器中单独处理。如果 juggler 不自己创建相关模型,请尝试这样做。
    • 我会单独发送相关数据在控制器中处理。感谢您的建议。
    猜你喜欢
    • 2019-12-02
    • 1970-01-01
    • 2019-08-13
    • 2019-08-27
    • 2021-03-10
    • 2019-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多