关系名称是指“有一个”的关系含义,这意味着对于每个用户,在位置表中存在一个(且只有一个)条目。每个用户在位置表中都有“一个”条目,并且如果您的数据需要显示两个用户具有相同的位置,则意味着位置表将存储具有不同用户ID的相同位置数据。这对于关系映射来说仍然非常好,并且允许您执行User.location调用。
您要查找的内容略有不同,这将是“位置hasMany用户”,因为您将与多个用户共享位置条目。请阅读“对于每个位置条目,许多用户可以共享它”。您必须以不同的方式进行查询,并在要返回包含位置数据的用户时使用include: ['location']
筛选器(否则您只会获取locationId值)。
关系建设者:
$ slc loopback:relation
? Select the model to create the relationship from: Location
? Relation type: has many
? Choose a model to create a relationship with: user
? Enter the property name for the relation: users
? Optionally enter a custom foreign key:
? Require a through model? No
location.json:
{
"name": "Location",
"base": "PersistedModel",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {
"lat": {
"type": "number"
},
"long": {
"type": "number"
}
},
"validations": [],
"relations": {
"users": {
"type": "hasMany",
"model": "user",
"foreignKey": "locationId"
}
},
"acls": [],
"methods": {}
}
这比我的答案要直截了当,我以为我尝试过'belongsTo'关系,但是必须已经切换模型或忘记清除旧模式。 – Brian
谢谢,这个作品完美。 – dominik