【问题标题】:Seed data to PSQL with Sequelize has different IDs every time seed script runs每次种子脚本运行时,带有 Sequelize 的 PSQL 的种子数据都有不同的 ID
【发布时间】:2018-12-16 18:42:13
【问题描述】:

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

models/index.js

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,
};

数据/index.js

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]],
  ]
}

种子数据库

#!/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 中 Genre 表如何播种的一个示例

postico seeding

【问题讨论】:

    标签: sequelize.js psql seeding


    【解决方案1】:

    我的问题是你依赖于 Sequelize 插入主键并为您生成默认 ID,这很好,但如果您这样做,则需要嵌套插入。对于 Country、State 表等种子数据,使用预生成的键和插入数据更容易。

    【讨论】:

    • 嗨,Brian,刚刚注意到我的收件箱,感谢您的回复。我尝试在模型中创建自己的主键,但遇到了同样的问题。但是我上面发布的种子文件不是已经嵌套插入了吗?我正在创建艺术家,然后是流派,然后为艺术家设置流派。
    猜你喜欢
    • 2018-07-21
    • 1970-01-01
    • 2013-11-18
    • 2021-06-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-09
    • 2017-06-06
    • 1970-01-01
    相关资源
    最近更新 更多