从连接表 javascript 填充种子数据

问题描述 投票:0回答:1

我有使用 knex 的迁移文件的代理、列表和潜在买家的种子数据。我创建了一个名为 listingsBuyers 的连接表,引用了列表和买家的外键。有没有办法为一个引用列表和买家的外键的连接表做种子?下面的设置方式给出了未定义的错误列表。

exports.up = function(knex) {
    return knex.schema.createTable('listings', table =>{
        table.increments()
        table.string('address')
        table.integer('agent_id')
        table.foreign('agent_id').references('agents.id')
    })
};

exports.down = function(knex) {
    return knex.schema
        .dropTable('listings')
};
exports.up = function(knex) {
    return knex.schema.createTable('buyers', table =>{
        table.increments()
        table.string('name')
        table.integer('listing_id')
        table.foreign('listing_id').references('listings.id')
    })
};

exports.down = function(knex) {
    return knex.schema
        .dropTable('buyers')
};

这是连接表

exports.up = function(knex) {
    return knex.schema.createTable('listingsBuyers', table =>{
        table.increments()
        table.integer('listing_id')
        table.foreign('listing_id').references('listings.id')
        table.integer('buyer_id')
        table.foreign('buyer_id').references('buyers.id')
    })
};

exports.down = function(knex) {
    return knex.schema
        .dropTable('listingsBuyers')
};

种子文件

exports.seed = function(knex) {
  return knex('listingsBuyers').insert([
    {listing_id: listings.id , buyer_id: buyers.id},
    //{listing_id: 2, buyer_id: 1},
    //{listing_id: 3, buyer_id: 3}
  ])
  .then(() =>{//set the value for auto-incrementing
    return knex.raw(`SELECT setval('listingsBuyers_id_seq', (SELECT MAX(id) FROM listingsBuyers))`)
  });
};
javascript join knex.js seeding
1个回答
0
投票

我怀疑以下情况:

exports.seed = function(knex) {
  return knex('listingsBuyers').insert([
    {listing_id: listings.id , buyer_id: buyers.id},
    //{listing_id: 2, buyer_id: 1},
    //{listing_id: 3, buyer_id: 3}
  ])

listings.id
(第 3 行)不会被定义,
buyers.id
也不会被定义。

不确定为什么要注释掉接下来的两行,因为它们可能确实有效。尝试:

exports.seed = function(knex) {
  return knex('listingsBuyers').insert([
    { listing_id: 2, buyer_id: 1 },
    { listing_id: 3, buyer_id: 3 }
  ])
© www.soinside.com 2019 - 2024. All rights reserved.