我正在使用PostgreSQL,Sequelize和Sequelize-cli。
在IDE中使用sequelize-cli和一些操作我设置了以下模型和迁移文件(简化了示例,我没有包含"用户"迁移文件):
模型文件
// models/annotation.js
module.exports = function (sequelize, DataTypes) {
var Annotation = sequelize.define('Annotation', {
userId: {
type: DataTypes.INTEGER,
references: {model: "User", key: 'id'},
},
url: DataTypes.STRING,
source: DataTypes.STRING,
body: DataTypes.TEXT,
exact: DataTypes.TEXT,
}, {
classMethods: {
associate: function (models) {
// associations can be defined here
Annotation.belongsTo(models.User, {foreignKey: "userId"});
},
},
});
return Annotation;
};
相应的迁移文件
// migrations/20161121050521-create-annotation.js
const User = require("../models/user");
module.exports = {
up: function(queryInterface, Sequelize) {
return queryInterface.createTable('Annotations', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
userId: {
type: Sequelize.INTEGER,
references: {model: User, key: 'id'},
allowNull: false
},
...
参考模型
// models/user.js
module.exports = function(sequelize, DataTypes) {
var User = sequelize.define('User', {
title: DataTypes.STRING,
name: DataTypes.STRING,
email: DataTypes.STRING,
}, {
classMethods: {
associate: function(models) {
// associations can be defined here
User.hasMany(models.Annotation, {foreignKey: "userId"});
}
}
});
return User;
};
我正在运行以下cli命令:
"dropdb -U postgres annotate && curl -XDELETE 'http://localhost:9200/_all'"
"createdb -U postgres annotate"
"node_modules/.bin/sequelize db:migrate"
当我迁移时,我收到以下错误:
SequelizeDatabaseError: relation "User" does not exist
从文档中我可以看出Annotation.belongsTo(models.User
足以建立关联,但是当我这样做时,我的数据库表没有任何外键字段。
如何建立彼此关联的表?