gpt4 book ai didi

mysql - 使用 Sequelize fixtures 导入具有嵌套关联的数据

转载 作者:行者123 更新时间:2023-11-30 22:13:22 25 4
gpt4 key购买 nike

我正在尝试使用 Sequelize Fixtures 编写导入脚本对于具有以下设置的规范化地址数据:

const Address = sequelize.define('address', { ... });
const Cities = sequelize.define('cities', { ... });
const Regions = sequelize.define('regions', { ... });

Address.belongsTo(Cities, {
foreignKey: 'cityId'
});

Cities.belongsTo(Regions, {
foreignKey: 'regionId'
});

下面是我尝试导入的数据示例:

区域导入数据:

╔═════════════╗
║ ID Region ║
╠═════════════╣
║ 1 England ║
╚═════════════╝

城市导入数据:

╔════════════╗
║ ID City ║
╠════════════╣
║ 1 London ║
╚════════════╝

地址导入数据:

╔═════════════════════════════════════════════════════════╗
║ ID Owner Address City Region ║
╠═════════════════════════════════════════════════════════╣
║ 1 Sherlock Holmes 221B Baker Street London England ║
╚═════════════════════════════════════════════════════════╝

首先,我导入地区数据,然后是引用该地区的城市数据:

// regions.json
[
{
"model": "Regions",
"data": {
"label": "England"
}
}
]

// cities.json
[
{
"model": "Cities",
"data": {
"label": "London",
"region": {
"label": "England"
}
}
}
]

这很好用,但是有没有一种方法可以导入地址数据,同时引用城市地区数据,以防止福尔摩斯住在伦敦,加州?我试过在城市内嵌套区域数据:

// address.json
[
{
"model": "Address",
"data": {
"street_1": "221B Baker Street",
"city": {
"label": "London",
"region": {
"label": "England"
}
}
}
}
]

更新#1

我试图变得聪明并使用 Sequelize.literal无济于事:

[
{
"model": "Address",
"data": {
"street_1": "221B Baker Street",
"cityId": {
"val": "SELECT c.id FROM cities c LEFT JOIN regions r ON c.regionId = r.id WHERE c.label = \"London\" AND r.label = \"England\""
}
}
}
]

最佳答案

我已经离开这个项目(已经 2 年了!),但最近更新了 Github issue我提交提醒我从项目所有者那里收到的我以前从未见过的回复。因此,为了解决这个问题并帮助将来可能遇到这个问题的任何人,这里是 the answer :

Haven't encountered this before. I think the only decent solution right now is to specify IDs for the cities and use those

我还没有验证解决方案,就像我说的那样,那是很久以前的事了,不记得我正在从事的项目,但请告诉我它是否适合你!

关于mysql - 使用 Sequelize fixtures 导入具有嵌套关联的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39277672/

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