gpt4 book ai didi

node.js - 如何通过sequelize queryInterface插入关联行

转载 作者:搜寻专家 更新时间:2023-11-01 00:37:12 24 4
gpt4 key购买 nike

我正在使用带有 sequelize 的 sequelize cli 为多对多连接表生成种子文件

这里我有 Users and Collections 和 User_Collections 作为连接表我已经为 Users 和 Collections 创建了 seeder 文件,但我想为连接表创建一个 seeder 文件。我如何动态访问 User 或 Collection 中行的 ID,以便我可以将该值插入连接表 bulkinsert

用户:



module.exports = {
up: (queryInterface, Sequelize) => queryInterface.bulkInsert('Users', [ {
first_name: 'John',
last_name: 'Doe',
email: 'john.doe@gmail.com',
password: 'testme',
createdAt: new Date(),
updatedAt: new Date(),
}], {}),
down: (queryInterface, Sequelize) => queryInterface.bulkDelete('Users', null, {}),
};

收藏



module.exports = {
up: (queryInterface, Sequelize) => queryInterface.bulkInsert('Collections', [{
collection_name: 'Test Collection1',
createdAt: new Date(),
updatedAt: new Date(),
}, {
collection_name: 'Test Collection2',
createdAt: new Date(),
updatedAt: new Date(),
}, {
collection_name: 'Test Collection3',
createdAt: new Date(),
updatedAt: new Date(),
}]),

down: (queryInterface, Sequelize) => queryInterface.bulkDelete('Collections', null, {}),
};

最佳答案

使用queryInterface.sequelize获取sequelize对象,然后查询需要的id

'use strict';
var Promise = require("bluebird");

module.exports = {
up: (queryInterface, Sequelize) => {
var sequelize = queryInterface.sequelize;
return Promise.all([
sequelize.query('SELECT id FROM users', { type: sequelize.QueryTypes.SELECT}),
sequelize.query('SELECT id FROM collections', { type: sequelize.QueryTypes.SELECT}),
]).spread((userids, collectionsids)=>{
var user_collections = [];
userids.forEach(userId=> {
collectionsids.forEach(collectionId =>{
user_collections.push({
user_id: userId.id,
collection_id: collectionId.id,
createdAt: new Date(),
updatedAt: new Date(),
})
});
});
return queryInterface.bulkInsert('User_Collections', user_collections, {});
})
},
down: (queryInterface, Sequelize) => {
return queryInterface.bulkDelete('User_Collections', null, {});
}
};

关于node.js - 如何通过sequelize queryInterface插入关联行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47367586/

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