database - 不需要 Sequelize 自动创建的 id 属性

标签 database sequelize.js

let data = require('./../../config/db')
let connection = data.connection
let sequelize = data.sequelize
let sql = function(){
    let clubMembers = connection.define('club_members',{
            position:{
                type :sequelize.ENUM('President','Treasurer') ,
                allowNull : false
            }
        },
        {
            classMethods : {
                associate : function(models){
                    let clubMembers = models.club_members
                    let club = models.club
                    let student = models.student
                    club.hasMany(clubMembers,{
                        foreignKey : "club_id"
                    })
                    student.hasMany(clubMembers,{
                        foreignKey : "student_id"
                    })
                }
            }
        }
    );
    return clubMembers;
}
module.exports = sql;

我不需要此表中的 id 属性,但 sequelize 会自动创建它。并且两个外键的组合应该被视为主键,即复合主键。
enter image description here

最佳答案

您应该在 belongsToMany 函数中使用 associate

associate: function(models){
    models.club.belongsToMany(models.student, { through: models.club_members, foreignKey: 'club_id' });
    models.student.belongsToMany(models.club, { through: models.club_members, foreignKey: 'student_id' });
}

这将使用由 club_membersclub_id 组成的复合主键创建 student_id 表,没有默认的 id 列。

关于database - 不需要 Sequelize 自动创建的 id 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42852130/

相关文章:

mysql - 将 MariaDB 数据库迁移到 MySQL 服务器

ios - NSUserDefaults 中的可变对象

SQL:对一列中的某些项目求和并从该列中的另一个数字中减去它

MySQL 使用 UNION 连接 3 个表

javascript - Sequelize错误: column reference "id" is ambiguous.无法在文档中找到答案

ios - 未实现的谓词 SQL 生成

mysql - 带计数的子选择

javascript - 类型错误 : Cannot read property 'findAll' of undefined (mariaDB, ExpressJs)

postgresql - 如何使用 postgresql 删除所有带有 Sequelize.js 的表?

node.js - Sequelize : set new uuid