我正在用MYSQL定义模型中的关联。但是在迁移之后,外键并没有像后缀文档中解释的那样被添加到目标模型中。
我还尝试在模型和迁移文件中手动定义外键,但仍然没有在表之间创建关联。当我在PhpMyAdmin中的relationship视图中查看表时,不会创建外键约束或关系。
我已经用SQLite和PostgreSQL尝试过同样的结果。我不知道我做错了什么。这是模特。
AURHOR MODEL
//One author hasMany books
'use strict';
module.exports = (sequelize, DataTypes) => {
const Author = sequelize.define('Author', {
Name: DataTypes.STRING
}, {});
Author.associate = function(models) {
// associations can be defined here
Author.hasMany(models.Book)
};
return Author;
};
我希望sequelize按文档中指定的方式在books表上添加authorId,但这没有发生。
BOOK MODEL
//Book belongs to Author
'use strict';
module.exports = (sequelize, DataTypes) => {
const Book = sequelize.define('Book', {
Title: DataTypes.STRING
}, {});
Book.associate = function(models) {
// associations can be defined here
Book.belongsTo(models.Author)
};
return Book;
};
在迁移之后,这两个表之间没有创建任何关联。我还试图在模型关联中定义自定义外键,如下所示:
//Author model
Author.hasMany(models.Book,{foreignKey:'AuthorId'})
//Book model
Book.belongsTo(models.Author,{foreignKey:'AuthorId'})
但这并不能解决问题
我已经开始在模型中定义外键,然后在关联中引用它们,如下所示:
'use strict';
module.exports = (sequelize, DataTypes) => {
const Book = sequelize.define('Book', {
Title: DataTypes.STRING,
AuthorId:DataTypes.INTEGER
}, {});
Book.associate = function(models) {
// associations can be defined here
Book.belongsTo(models.Author,{foreignKey:'AuthorId'})
};
return Book;
};
但是仍然没有建立任何协会。
我最后决定在迁移文件中添加引用,如下所示:
'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
},
AuthorId:{
type: Sequelize.INTEGER,
references:{
model:'Author',
key:'id'
}
}
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
down: (queryInterface, Sequelize) => {
return queryInterface.dropTable('Books');
}
};
但是,当我运行这种迁移设置时,我得到了以下错误: error:无法创建表dbname
.books
(errno: 150“外键约束是我错误形成的”)
当我切换到PostgreSQL时,也会出现类似的错误。
我被这个问题耽搁了很长时间。我能做错什么。我使用的是版本4.31.2的后缀和sequelize。
发布于 2019-05-06 18:05:53
我在移民中错误地引用了模特。错路
AuthorId:{
type: Sequelize.INTEGER,
references:{
model:'Author',
key:'id'
}
}
校正方式
// Notes the model value is in lower case and plural just like the table name in the database
AuthorId:{
type: Sequelize.INTEGER,
references:{
**model:'authors',**
key:'id'
}
}
这解决了我的问题。现在正在对这些关联进行定义。
https://stackoverflow.com/questions/55991994
复制相似问题