我正在与一个朋友一起开发一个页面应用程序(在React中,但我相信框架并不重要,同样的问题也适用于Angular)。
有一个包含2个表的数据库:
两个表都以多对多关系连接到数据库中。
我们在将数据从后端传递到前端的方式有所不同(更准确地说,是CarManagementComponent,它将使用户能够处理汽车/功能(编辑/更新/删除等))。实际上,我们希望能够执行一些操作,然后再将请求发送回后端以更新数据库,以便用户具有类似于桌面应用程序的界面体验。
请记住,数据库中还有更多表,但为简单起见,我们在这里只讨论其中的两个表。
1)我的方法:
{
"Features": [
{
"Id": 0,
"Price": 3000,
"Name": "led lights",
"Color": "transparent",
"Brand": "Valeo",
"Guarantee": 12
},
{
"Id": 1,
"Price": 1000,
"Name": "air conditioning",
"Color": "",
"Brand": "Bosch",
"Guarantee": 12
},
{
"Id": 2,
"Price": 600,
"Name": "tinted windows",
"Color": "",
"Brand": "Bosch",
"Guarantee": 36
}
],
"Cars": [
{
"Id": 0,
"Name": "Ford Mustang GT",
"Weight": 2210,
"Features":[
{
"Id": 0, // id of many-to-many relations record
"FeatureId": 2
},
{
"Id": 1, // id of many-to-many relations record
"FeatureId": 1
}
]
},
{
"Id": 1,
"Name": "Volkswagen Arteon",
"Weight": 1650,
"Features":[
{
"Id": 2, // id of many-to-many relations record
"FeatureId": 2
}
]
}
]
}
2)我朋友的做法:
{
"Cars": [
{
"Id": 0,
"Name": "Ford Mustang GT",
"Weight": 2210,
"Features": [
{
"Id": 1,
"Price": 1000,
"Name": "air conditioning",
"Color": "",
"Brand": "Bosch",
"Guarantee": 12
},
{
"Id": 2,
"Price": 600,
"Name": "tinted windows",
"Color": "",
"Brand": "Bosch",
"Guarantee": 36
}
]
},
{
"Id": 1,
"Name": "Volkswagen Arteon",
"Weight": 1650,
"Features": [
{
"Id": 2,
"Price": 600,
"Name": "tinted windows",
"Color": "",
"Brand": "Bosch",
"Guarantee": 36
}
]
}
]
}
我相信第一种方法更好,因为:
我的朋友说第二种方法更好,因为:
您怎么看?哪种解决方案更好?也许他们两个都在某些地区?也许有我们没有想到的第三个解决方案?
答案 0 :(得分:5)
我想说,我最喜欢的方法是您的,主要有两个原因:
FeatureId
放置在汽车对象中,足以以有效的性能O(N)获得该功能。为使其更好,您可以将特征结构更改为此:
"Features": {
0: { // <- If the id is unique, you can use it as a key.
"Id": 0,
"Price": 3000,
"Name": "led lights",
"Color": "transparent",
"Brand": "Valeo",
"Guarantee": 12
},
1: {
"Id": 1,
"Price": 1000,
"Name": "air conditioning",
"Color": "",
"Brand": "Bosch",
"Guarantee": 12
},
2: {
"Id": 2,
"Price": 600,
"Name": "tinted windows",
"Color": "",
"Brand": "Bosch",
"Guarantee": 36
}
},
这样,您可以在O(1)中获得特征。