Hid*_*ide 6 node.js sequelize.js
我用 Node.js 制作了 API 服务器。
我还使用sequelize(版本4)与MySQL 进行通信。
我的数据库结构是简单的遵循系统。
[模型.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
})
Run Code Online (Sandbox Code Playgroud)
听说如果没有选项的话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'});
Run Code Online (Sandbox Code Playgroud)
我想参考用户的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;
Run Code Online (Sandbox Code Playgroud)
为什么还引用用户的no专栏?
我该如何解决这个问题?
谢谢。
targetKey与belongsTo()
You are using一起使用belongsToMany(),因此根据sequelize doc,您应该使用otherKey而不是targetKey:
User.belongsToMany(User, { as: 'follower', through: 'follow', foreignKey: 'follower_id', otherKey: 'userid'});
User.belongsToMany(User, { as: 'following', through: 'follow', foreignKey: 'following_id', otherKey: 'userid'});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3767 次 |
| 最近记录: |