我正在尝试将likeId附加到sequelize中的posts表中。理想情况下,我希望通过引用models.Post
来检索喜欢的人数。尽管我的桌子设置方式。我的桌子给我这个
LikeId未附加到posts列,我可能做错了什么?
我做到了
sequelize db:migrate:undo:all
sequelize db:migrate
模型/帖子
module.exports = (sequelize, DataTypes) => {
const Post = sequelize.define('Post', {
title: DataTypes.STRING,
post_content: DataTypes.STRING,
username: DataTypes.STRING
}, {});
Post.associate = function(models) {
Post.belongsTo(models.User, { foreignKey: 'userId', targetKey: 'id' });
Post.hasMany(models.Likes, { foreignKey: 'postId', targetKey: 'id' });
};
return Post;
};
模型/喜欢
'use strict';
module.exports = function(sequelize, DataTypes) {
const Like = sequelize.define('Likes', {
like:{
type:DataTypes.BOOLEAN,
allowNull:true
}
}, {});
Like.associate = function(models) {
Like.belongsTo(models.User, {
onDelete: "CASCADE",
foreignKey: {
foreignKey: 'userId'
}
})
Like.belongsTo(models.Post, {
onDelete: "CASCADE",
as:'post',
foreignKey: 'postId'
})
}
return Like;
};
迁移
创建类似迁移
'use strict';
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.createTable('Likes', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
like: {
type: Sequelize.BOOLEAN
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
},
});
},
down: (queryInterface, Sequelize) => {
return queryInterface.dropTable('Likes');
}
};
add-postId-to-likes
'use strict';
module.exports = {
up: function (queryInterface, Sequelize) {
return queryInterface.addColumn(
'Likes',
'postId',
{
type: Sequelize.INTEGER,
allowNull: false,
references: {
model: 'Posts',
key: 'id'
}
}
)
},
down: function (queryInterface, Sequelize) {
return queryInterface.removeColumn(
'Likes',
'postId'
)
}
};