序列化:创建表,但不创建外键

时间:2019-07-25 12:58:46

标签: node.js postgresql sequelize.js

我用Sequelize和PostgresSQL创建了一个node.js API。但是,当我启动应用程序时,没有创建外键。

首先,我异步编码schema.js文件。一切都很好(创建了外键)。但是由于某些外键是在表之前创建的,所以会发生错误。对于集成测试来说很烦人,在该测试中我多次删除并创建表。我必须编写一个同步的schema.js。

但是当我这样做时,我没有外键。

Schema.js:

"use strict"

const Sequelize = require('sequelize');

let sql = {
  user: "user",
  password: "pswd",
  host: "localhost",
  dbname: "superdb"
} 

let conString = "postgres://"+sql.user+":"+sql.password+"@"+sql.host+"/"+sql.dbname;

let sequelize = new Sequelize(conString, { logging: false });


  let Client = sequelize.define('client', {
    id: {type: Sequelize.INTEGER, primaryKey: true, allowNull: false,  autoIncrement: true},
    name: {type: Sequelize.STRING, allowNull: true}
  })

  let Pack = sequelize.define('pack', {
    id: {type: Sequelize.INTEGER, primaryKey: true, allowNull: false,  autoIncrement: true},
    brand: {type: Sequelize.STRING, allowNull: true},
    format: {type: Sequelize.STRING, allowNull: true},
  })

  let Cell = sequelize.define('cell', {
    id: {type: Sequelize.INTEGER, primaryKey: true, allowNull: false,  autoIncrement: true},
    voltage: {type: Sequelize.FLOAT, allowNull: true}
  })

  Promise.all([Client.sync({sync: true}), Pack.sync({sync: true}), Cell.sync({sync: true})])
  .then(() => {
    return Promise.all([
    Pack.belongsTo(Client),
    Cell.belongsTo(Pack),
  ])
  }).then(() => {
    return Promise.all([Client.sync({sync: true}), Pack.sync({sync: true}), Cell.sync({sync: true})])
  })

您可以执行node schema.js重现该错误。

所以,我得到了:

corn=# SELECT * FROM packs; 
 id | brand | format | createdAt | updatedAt 
----+-------+--------+-----------+-----------
(0 rows)

未创建clientId。我做错了什么?

0 个答案:

没有答案
相关问题