gpt4 book ai didi

javascript - 多行插入的嵌套数组正在使用 sequelize nodejs 进行字符串化

转载 作者:行者123 更新时间:2023-12-03 22:26:24 25 4
gpt4 key购买 nike

根据一些答案,我使用这种类型的数组在 mysql 中插入多行

[ [ 252456, 1, 55, '0' ],
[ 357083, 1, 56, '0' ],
[ 316493, 1, 57, '0' ] ]

所以在这个预期的结果是
INSERT INTO table (col1, col2, col3, col4) VALUES (252456,1,55,'0'), (357083,1,56,'0'), (316493,1,57,'0')

但实际查询正在运行的是
INSERT INTO table (col1, col2, col3, col4) VALUES 252456,1,55,'0',357083,1,56,'0',316493,1,57,'0'

有人能帮他解决问题吗??下面是我的代码片段
let get_rows = await db.sequelize.query("select col1, col1, col3, '0' as col4 from table1 where (condition1 = '3' || condition2 = '4') and condition3 = '0';", {replacements: [], type: db.sequelize.QueryTypes.SELECT});

if(get_rows && get_rows.length){
let insert_rows = get_rows.map(x => Object.values(x));

await db.sequelize.query("INSERT INTO table (col1, col2, col3, col4) VALUES ?;", {replacements: [insert_rows], type: db.sequelize.QueryTypes.INSERT});
};

最佳答案

如果为此使用 ORM(Sequelize),为什么要逐个字符串手动构建查询?

试试 Model.bulkCreate

要使用 bulkCreate 首先按如下方式准备数据

const rawData = [
[ 252456, 1, 55, '0' ],
[ 357083, 1, 56, '0' ],
[ 316493, 1, 57, '0' ]
];

const convertedData = rawData.map(arrObj => {
return {
col1: arrObj[0],
col2: arrObj[1],
col3: arrObj[2],
col4: arrObj[3]
}
})

然后只需将其提供给您的 Sequelize 模型,如下所示
await Table1Model.bulkCreate(convertedData)

关于javascript - 多行插入的嵌套数组正在使用 sequelize nodejs 进行字符串化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59064427/

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