首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >每次种子脚本运行时,带Sequelize的PSQL种子数据都具有不同的ID

每次种子脚本运行时,带Sequelize的PSQL种子数据都具有不同的ID
EN

Stack Overflow用户
提问于 2018-12-17 02:42:14
回答 1查看 145关注 0票数 0

我有一个seedDB脚本将数据输入到我的PSQL数据库中。大部分数据都很好,但每次运行seed:db脚本时,类型表和的in都不同。艺术家表的顺序与我的数据中的数组的顺序相同,但其余的表每次都是以杂乱的顺序播种的。这是一个问题,因为我根据ID进行关联,所以每次运行该文件时,这些关联都不同。如何为数据库设置种子,以便每次I都相同,并且可以进行正确的关联?

models/index.js

代码语言:javascript
运行
复制
require('dotenv').config();

const Sequelize = require('sequelize');

const db = new Sequelize(
  process.env.DATABASE_URL,
{
    underscored: true,
    returning: true,
  },
);

const Artist = db.define('artist', {
  name: {
    type:      Sequelize.STRING(128),
    allowNull: false,
    unique: true,
  },
  desc: {
    type:       Sequelize.TEXT,
    allowNull:  false,
  },
  img_url: {
    type:       Sequelize.TEXT,
    allowNull:  false,
  },
});

const Genre = db.define('genre', {
  name: {
    type:      Sequelize.STRING(64),
    allowNull: false,
    unique: true,
  },
});

const Album = db.define('album', {
  name: {
    type:      Sequelize.STRING(128),
    allowNull: false,
  },
  img_url: {
    type:       Sequelize.TEXT,
    allowNull:  false,
  },
});

const Show = db.define('show', {
  date: {
    type:     Sequelize.DATEONLY,
    allowNull:  false,
  },
  venue: {
    type:      Sequelize.STRING(64),
    allowNull: false,
  },
});

//associations
Show.belongsToMany(Artist, { through: 'artist_show_xref'});
Artist.belongsToMany(Show, { through: 'artist_show_xref'});

Genre.belongsToMany(Artist, { through: 'artist_genre_xref'});
Artist.belongsToMany(Genre, { through: 'artist_genre_xref'});

Artist.hasMany(Album);
Album.belongsTo(Artist);

module.exports = {
    Artist, 
    Genre, 
    Album, 
    Show, 
    db,
};

data/index.js

代码语言:javascript
运行
复制
module.exports = {
//name, desc, img_url, [genre1,genre2,genre3]
  artists: [
    ['Jachary', 'Originally from Boston, 25-year-old Jachary is now based in Bushwick, New York. On his debut album, "There\'s A Virus Going On" he plays most of the instruments, produces, and does vocals on each track. His versatility when it comes to every aspect of creating music allowshim to craft a unique sound that blends elements from funk, rock, and hip hop.','http://www.allthingsgomusic.com/wp-content/uploads/2017/07/Jachary-1.jpg',["Funk","Jazz"]],
    ['Jazze Belle', 'Jazze Belle is a duo comprised of producer/instrumentalist Jett and singer/songwriter Taylor Simone. Both hail from different parts of the country (Taylor\'s from LA and Jett\'s from Richmond), but the two share a sound influenced by jazzy vocals, soulful chords, and hip hop digital production. Playing everywhere in NYC from Nola, Darling to Baby\'s All Right, they are equipped with a musical tenacity and talent to match.','https://pbs.twimg.com/profile_images/837340614765207552/wEDG12iC_400x400.jpg',["Experimental","Jazz"]],
    ['Jelani Sei', 'One of the few bands in the northeast that can lull you with ethereal soundscapes while simultaneously sending you into a a crazy mosh, Jelani Sei is a group of individuals who are constantly searching the realms of harmony to find that new groove. Jelani Sei represents not only unity, but love, passion and a drive to push oneself beyond limits they didn\'t think they were capable of.','https://f4.bcbits.com/img/0011355358_10.jpg',["Soul","Funk"]],
    ['L\'Rain', 'Lead by composer and multi-instrumentalist Taja Cheek, L\'Rain puts on a special performance as a quartet. Hailed by the New York Times as a \'one-woman studio band\' L\'Rain puts on one of the best experimental live shows in the whole city','https://www.tinymixtapes.com/sites/default/files/imagecache/Article_Width/1707/dsc_1619-2.jpg',["Jazz","Alt-rock"]],
    ['Space Captain', 'Space Captain is a Brooklyn based psych-soul group signed to UK indie label Tru Thoughts.In a period of open-minded experimentation via live shows and studio jams, Space Captain have alighted on a progressive fusion of R&B and psychedelic rock with tentacles spinning out into soul, hip hop, electronica and noise.','http://nyc.thedelimagazine.com/sites/upload-files/20292747_1921203848119544_6591279462890360259_n.jpg',["Alt-rock"]],
    ['Star the Moonlight','Star the Moonlight is a neo-soul band straight from the outer rim, brimming with lush timbres and harmonies and driven by the powerful rhythmic interplay of interlocking grooves. Inspiration is taken from Richard Strauss, Frank Zappa and Dirty Projectors to create a mind melding mix of synthetic and acoustic textures, like a Van Gogh reimagined','https://scontent-lga3-1.xx.fbcdn.net/v/t31.0-8/15167686_1340660815979083_340349751037127786_o.jpg?_nc_cat=0&_nc_eui2=AeF0q35rPri5id6u4fo1Y_Fc59kJHrsCdRXXm-vXfbEUeqY79l5CkO70LTp4UVMxoPq7ESYShH5HjY5zQD3N5MErMysecAlCCdWlgTLkGJkJdw&oh=cec12280fd397db14e9b968b8e467ccc&oe=5BE6F690',["Jazz","Alt-rock"]],
    ['Valipala','Based in NYC since 2012, Valipala (formerly known as With Snack) tips their hats to the great groove makers of yesteryear while continuing to rethink modern R&B with a union of funk, jazz, and progressive rock. Known for their virtuosic arrangements and animated live shows, a night with Valipala is bound to somehow leave you both exhausted and energized.','https://d3jjg4nf4bbybe.cloudfront.net/u/300963/4f1ab18853472ef82ec986b1ea5ceffcf2989979/original/valipalamayshoot5.jpg/!!/b:W1sicmVzaXplIiw2NzBdLFsibWF4Il0sWyJ3ZSJdXQ==.jpg',["Soul","Funk"]],
    ['Vinegar Mother','Vinegar Mother is carving  its own niche up and down the East Coast\'s live music circuit. The psychedelic soul-rock  quintet has attracted fans from Brooklyn to Burlington, and  everywhere  in  between.','https://s3.amazonaws.com/static.imposemagazine.com/wp-content/uploads/2018/03/Vinegar-Mother-Hi-Res-1024x683.jpg',["Funk","Jazz","Soul"]],
    ['Woolly Mammals','Woolly Mammals is an alternative-soul quartet from Brooklyn, New York. Since their debut release, \'Cheap Talk\' in January 2017 the band has received praise from Rolling Stone France, No Treble Magazine, Live for Live Music, and Nextbop. With the recent release of their debut EP, When You Get This, in January 2018, the band continues to deliver their own haughtily original brand of techno-funk, layering a talking bass vocoder on top ofsoaring synthesizers, swampy subs, and acid-jazz backbeats.','https://pbs.twimg.com/media/DJSyIcWXkAAO98R.jpg',["Jazz"]],
    ['Panther Hollow','Led by singer-songwriter Bernardo Ochoa, Panther Hollow combines elements of grunge, indie rock and folk.',"https://f4.bcbits.com/img/0009339227_10.jpg",["Indie-rock","Folk","Punk"]],  
    ['Renata Zeiguer', 'Renata Zeiguer is a Brooklyn-based multi-instrumentalist singer-songwriter, the daughter of Argentinean and Philippine immigrants. An NYC native, she grew up playing classical and jazz music, beginning on the violin and the piano at age 6, and listening to her grandmother play ragtime and tango music obsessively on a baby grand during family visits in Buenos Aires.', 'https://static1.squarespace.com/static/58b8a99fd1758e4cc2690804/t/5b56279c352f536f231f175d/1532372903944/Renata+Zeiguer-5941.jpg',['Alt-rock','Indie-rock']],  
    ['Madison McFerrin','Brooklyn-based singer/songwriter, Madison McFerrin, is described by the New York Times as "show[ing] wonderful vocal dexterity, deftly swerving from sharp, clearly enunciated staccato bursts to fluttery, free-form melismata.','https://assets.rbl.ms/18274061/980x.jpg',['Soul','R&B']]
  ],
  //genre name
  genres: [
  ['Funk'],
  ['Jazz'],
  ['Soul'],
  ['Alt-rock'],
  ['Experimental'],
  ['Hip-hop'],
  ['Indie-rock'],
  ['Electronic'],
  ['Psychedelic'],
  ['R&B'],
  ['Punk'],
  ],

  //name,img_url,artist
  albums:[
    ['Mango City', 'https://f4.bcbits.com/img/a3147368541_10.jpg',7],
    ['All Flowers In Time', 'https://f4.bcbits.com/img/a0708663422_10.jpg',5],
    ['There\'s a Virus Going On','https://f4.bcbits.com/img/a0703511586_10.jpg',1],
    ['Go To Bed Standing Up','https://i1.sndcdn.com/artworks-000209628840-dh3giq-t500x500.jpg',2],
    ['LVNDR TWN', 'https://f4.bcbits.com/img/a0918581716_10.jpg', 3],
    ['L\'Rain','https://f4.bcbits.com/img/a0453705262_16.jpg', 4],
    ['Haven\'t You Heard', 'https://f4.bcbits.com/img/a2742014305_16.jpg', 6],
    ['Phases','https://f4.bcbits.com/img/a0762015821_16.jpg',8],
    ['When You Get This', 'https://millsrecordcompany.com/Photo/418458928650:500', 9],
    ['People Synestesia','https://f4.bcbits.com/img/a1114866823_10.jpg',10],
    ['Old Ghost','https://f4.bcbits.com/img/a0430570891_16.jpg',11],
    ],
//date, venue, [artists in show]
  shows:[
   ['2018-10-26', 'Coney Island Baby', [1,3]],
   ['2018-11-06', 'C\'mon Everybody', [5]],
   ['2018-11-08', 'Pianos', [2,6,7]],
   ['2018-11-08', 'Mercury Lounge', [9,11]],
  ]
}

seedDB

代码语言:javascript
运行
复制
#!/usr/bin/env node
const { Artist, Genre, Album, Show, db } = require('../models');
const { artists, genres, albums, shows } = require('../data');


(async () => {
  await Promise.all(artists.map(async ([name, desc, img_url, genres]) => {
    try {
      const newArtist = await Artist.create({ name, desc, img_url });
      const newGenres = await Promise.all(genres.map(name =>
        Genre.findOrCreate({ where: { name } }).then(([g]) => g)));
      return newArtist.setGenres(newGenres);
    } catch (e) {
      throw (e.message);
    }
  }));

  await Promise.all([
    Album.bulkCreate(albums.map(([name, img_url, artist_name]) => ({ name, img_url, artist_name }))),
    Promise.all(shows.map(async ([date, venue, artists]) => {
      const newShow = await Show.create({ date, venue });
      return newShow.setArtists(artists);
    })),
  ]);     
  db.close();
})();

这里有一个例子,展示了Postico中的流派表格是如何播种的

postico seeding

EN

回答 1

Stack Overflow用户

发布于 2018-12-22 06:37:47

问题I是,您依赖Sequelize来插入主键并为您生成默认it,这很好,但如果您这样做,则需要嵌套插入。对于像Country、State表这样的种子数据,更容易使用预先生成的键并与数据一起插入。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53805346

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档