在节点/ sequelize cli中为两个单独的表和连接表插入数据的最佳方式或方式是什么?
即。我有一个地址表,我在这里添加
const faker = require('faker');
const models = require('./server/db/sequelize/models');
const States = models.States;
const Addresses = models.Addresses;
module.exports = {
up: (queryInterface) => {
return Promise.all([
for (let i = 0; i < 1000; i++) {
Addresses.create({
streetName: faker.address.streetAddress(),
streetNameAlt: faker.address.streetAddress(),
zipCode: faker.address.zipCode(),
town: faker.address.county(),
city: faker.address.city(),
stateId: id,
addressTypeId: 1,
createdAt: faker.date.recent(),
updatedAt: faker.date.recent(),
});
}
},
down: (queryInterface) => {
return queryInterface.bulkDelete('Addresses', null, {});
}
};
然而,当我生成一个用户时,我想从我的地址表中选择一个随机地址作为addressId并创建一个联合记录
即
const faker = require('faker');
const usersList = [];
for (let i = 0; i < 1000; i++) {
const userObj = {
email: faker.internet.email(),
password: faker.internet.password(),
name: faker.name.findName(),
gender: 'Male',
description: '',
location: faker.address.streetAddress(),
website: faker.internet.url(),
};
usersList.push(userObj);
}
单独代码
UserAddress.create({
userId: userId,
addressId: addressId
});
答案 0 :(得分:3)
//Another way to do this, easy and fast with random data
'use strict';
var faker = require("faker");
module.exports = {
up: (queryInterface, Sequelize) => {
var newData = [];
for (let i = 0; i < 10; i++) {
const seedData = {
country_name: faker.address.country(),
country_code: faker.address.countryCode(),
createdAt: new Date(),
updatedAt: new Date()
};
newData.push(seedData);
}
return queryInterface.bulkInsert('Countries', newData);
},
down: (queryInterface, Sequelize) => {
return queryInterface.bulkDelete('Countries', null, {});
}
};
答案 1 :(得分:0)
您可以简单地查询地址列表',将所有ID放入数组中并随机选择一个
const allAddress = models.Addresses.findAll();
const allIds = allAddress.map(x => x.id);
const rand = allIds[Math.floor(Math.random() * allIds.length)];
UserAddress.create({
userId: userId,
addressId: rand
});