在 LoopBack 中查询 Reference/lookup 个值

Query Reference/lookup values in LoopBack

您如何查询 reference/lookup 数据以及在支持它们的模型之间构建的正确关系是什么?

示例:

地址模型有一个字段代表地址所在的城市。城市模型有一个预先填充的城市列表。我想在两个模型之间建立环回关系,这样我就可以在添加新地址和查询地址时引用城市 return 城市作为地址的一部分。

在关系数据库中,你可以有一个外键,比如用对城市的引用填充的 CityId。然后,您可以查询地址 table 并将城市 table 连接到与该地址相关的城市 return。

在环回中,我有以下模型(为了示例而缩减):

地址模型

{
    "name": "Address",
    "base": "PersistedModel",
    "idInjection": true,
    "options": {
        "validateUpsert": true
    },
    "properties": {
        "addressLineOne": {
            "type": "string",
            "required": true
        },
    },
    "validations": [],
    "relations": {    
        "city": {
            "type": "hasOne",
            "model": "city",
            "foreignKey": "cityId"
        }
    },
    "acls": [],
    "methods": {}
}

城市模式

{
    "name": "City",
    "base": "PersistedModel",
    "idInjection": true,
    "options": {
        "validateUpsert": true
    },
    "properties": {
        "cityName": {
            "type": "string",
            "required": true
        }
    },
    "validations": [],
    "relations": {},
    "acls": [],
    "methods": {}
}

对于地址模型,将关系从 hasOne 更改为 belongsTo:

...
"relations": {    
    "city": {
        "type": "belongsTo",
        "model": "City",
        "foreignKey": "cityId"
    }
}
...

BelongsTo 关系将外键添加到地址模型。所以每个地址都会有一个 cityId。

对于 City 模型,您可以像这样添加关系:

"relations": {    
    "addresses": {
        "type": "hasMany",
        "model": "Address",
        "foreignKey": "cityId"
    }
}

现在您将能够获取任何城市的所有地址。

P.S。我很确定在配置关系时,您需要为模型使用确切的模型名称:"model": "City" 或 "model": "Address",就像您在模型中设置的一样描述:

{
   "name": "Address",
   "base": "PersistedModel",
   "idInjection": true,
...