gpt4 book ai didi

javascript - 环回多个一对多关系

转载 作者:太空宇宙 更新时间:2023-11-04 16:30:07 25 4
gpt4 key购买 nike

我已经开始接触 Loopback,并且对模型关系声明有点困惑。

示例模型

  • 名字
  • 姓氏
  • idcountrybirth//引用国家/地区表
  • idcountrynationality//再次引用国家/地区表

请注意,idcountrybirthidcountrynationality 可以为 Person 的每个实例引用不同的县

上述关系

我一直在为 2 个国家/地区字段中的每一个字段寻找类似于 hasA 的内容,但这种关系并不存在。

我需要在“国家/地区人员”上设置什么样的关系?

这是我当前 ERD 的示例模型,我正在尝试基于 Loopback 对其进行修改。

screenshot of ERD diagram showing one to many relationships on 2 fields in Person table, related with Country table

最佳答案

您可以为每个使用 hasOne 关系。不要将 idcountrybirthidcountrynationality 定义为属性,因为它们都表示 PersonCountry 之间的关系。

{
"name": "Person",
"base": "PersistedModel",
"idInjection": true,
"properties": {
"firstname": {
"type": "string"
},
"lastname": {
"type": "string"
}
},
"validations": [],
"relations": {
"birthCountry": {
"type": "hasOne",
"model": "Country",
"foreignKey": "birthCountryId"
},
"nationality": {
"type": "hasOne",
"model": "Country",
"foreignKey": "nationalityCountryId"
},
},
"acls": [],
"methods": []
}

然后,使用 REST API

POST /api/Person
{
"firstname": "R.",
"lastname" : "Federer"
}

然后,指定他的出生国家

POST /api/Person/1/birthCountry
{
"name": "Switzerland"
}

还有国籍

POST /api/Person/1/nationality
{
"name": "South Africa"
}

有些人有多个国籍,因此您可以使用 hasMany 关系代替 hasOne 作为 nationality 关系;)

关于javascript - 环回多个一对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39885755/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com