我正在研究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');
}
};
创建作者和作者之间关系的迁移本书:
'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'
)
}
};
这些是我的模型:
author.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"
我是续集的新手,我们将不胜感激!
答案 0 :(得分:4)
您已经创建了Authors
表,但是用小的a
引用了该表。应该是
references: {
model: 'Authors',
key: 'id'
},
答案 1 :(得分:0)
我正面临类似的问题,所以我如何实现它-
复制该迁移文件中的代码并删除迁移文件。
然后,我生成了一个新的迁移文件,并粘贴了我先前复制并运行sequelize db:migrate
的代码。