【发布时间】:2018-11-29 17:07:14
【问题描述】:
我正在处理 Author hasMany Books 示例并尝试运行 sequelize-cli 迁移,但在运行以下迁移时遇到以下问题:
ERROR: relation "authors" does not exist
这是创建作者的第一个迁移:
'use strict';
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.createTable('Authors', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
firstName: {
type: Sequelize.STRING
},
lastName: {
type: Sequelize.STRING
},
dateOfBirth: {
type: Sequelize.DATEONLY
},
dateOfDeath: {
type: Sequelize.DATEONLY
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
down: (queryInterface, Sequelize) => {
return queryInterface.dropTable('Authors');
}
};
创建书籍的第二次迁移:
'use strict';
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.createTable('Books', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
title: {
type: Sequelize.STRING
},
summary: {
type: Sequelize.STRING
},
isbn: {
type: Sequelize.STRING
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
down: (queryInterface, Sequelize) => {
return queryInterface.dropTable('Books');
}
};
在 Author 和 Book 之间创建关系的迁移:
'use strict';
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.addColumn(
'Books', // name of source model
'AuthorId',
{
type: Sequelize.INTEGER,
references: {
model: 'authors',
key: 'id'
},
onUpdate: 'CASCADE',
onDelete: 'SET NULL'
}
)
},
down: (queryInterface, Sequelize) => {
return queryInterface.removeColumn(
'Books',
'AuthorId'
)
}
};
这些是我的模型:
作者.js:
'use strict';
module.exports = (sequelize, DataTypes) => {
var Author = sequelize.define('Author', {
firstName: { type: DataTypes.STRING, allowNull: false, len: [2, 100] },
lastName: { type: DataTypes.STRING, allowNull: false },
dateOfBirth: { type: DataTypes.DATEONLY },
dateOfDeath: { type: DataTypes.DATEONLY }
}, {});
Author.associate = function (models) {
// associations can be defined here
Author.hasMany(models.Book);
};
return Author;
};
book.js:
'use strict';
module.exports = (sequelize, DataTypes) => {
var Book = sequelize.define('Book', {
title: { type: DataTypes.STRING, allowNull: false, len: [2, 100], trim: true },
summary: { type: DataTypes.STRING, allowNull: false },
isbn: { type: DataTypes.STRING, allowNull: false }
}, {});
Book.associate = function (models) {
// associations can be defined here
Book.belongsTo(models.Author);
};
return Book;
};
我尝试了各种方法都无济于事。我的猜测是它正在尝试以异步方式更改表,但之前的迁移运行并完成了:
我正在使用以下内容:
"pg": "^7.4.3"
"sequelize": "^4.37.10"
"sequelize-cli": "^4.0.0"
"express": "~4.16.0"
我是续集的新手,任何帮助将不胜感激!
【问题讨论】:
标签: postgresql sequelize.js sequelize-cli