【发布时间】:2018-07-18 12:16:15
【问题描述】:
我用 Node.js 制作了 API 服务器。
我还使用 sequelize(version 4) 与 MySQL 进行通信。
我的数据库结构是简单的跟随系统。
[model.js]
export const User = sequelize.define('user', {
no: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
userid: {
type: Sequelize.STRING,
allowNull: false,
unique: true
},
userpw: {
type: Sequelize.STRING,
allowNull: false
}
}, {
freezeTableName: true,
underscored: true
})
听说如果targetKey没有选项,会自动引用主键。
但如果targetKey 存在,请参阅该列。
所以我这样定义关联。
User.belongsToMany(User, { as: 'follower', through: 'follow', foreignKey: 'follower_id', targetKey: 'userid'});
User.belongsToMany(User, { as: 'following', through: 'follow', foreignKey: 'following_id', targetKey: 'userid'});
我想推荐用户的userid。但是我运行它之后,它仍然引用no(PK)。
在控制台中执行的查询在这里。
CREATE TABLE IF NOT EXISTS `follow` (`created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL, `follower_id` INTEGER , `following_id` INTEGER , PRIMARY KEY (`follower_id`, `following_id`), FOREIGN KEY (`follower_id`) REFERENCES `user` (`no`) ON DELETE CASCADE ON UPDATE CASCADE, FOREIGN KEY (`following_id`) REFERENCES `user` (`no`) ONDELETE CASCADE ON UPDATE CASCADE) ENGINE=InnoDB;
为什么还要引用用户的no专栏?
我该如何解决这个问题?
谢谢。
【问题讨论】:
标签: node.js sequelize.js