【问题标题】:sequelize.js belongsToMany on non-primary keysequelize.js 非主键上的 belongsToMany
【发布时间】: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


    【解决方案1】:

    targetKeybelongsTo() 一起使用 你正在使用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'});
    

    【讨论】:

      【解决方案2】:

      5.15.0 开始,已为sourceKeytargetKey 添加了对多对多关系的支持。文档中的This page 提供了此用例的示例(在页面底部)。

      查看my answer here了解更多详情。

      【讨论】:

        猜你喜欢
        • 2017-07-08
        • 2017-03-02
        • 2018-01-31
        • 1970-01-01
        • 2012-12-19
        • 1970-01-01
        • 2019-11-22
        • 2010-10-08
        • 2013-08-28
        相关资源
        最近更新 更多