Phil
Phil

Reputation: 11175

Compound/Composite key association with Sequelize

Does anyone know how I can use compound keys to relate to a table using Sequelize and their built in relationships?

I have tried useing primaryKey: true and unique: with no avail.

Upvotes: 0

Views: 3145

Answers (1)

Vivek Doshi
Vivek Doshi

Reputation: 58603

Here is the example , how you can define composite key in sequlize

sequelize.define('item_likes',{
    item_id:{
        type: db.Sequelize.INTEGER,
        allowNull: false,
        unique:"liked_user" // this will create composite key
    },
    user_id:{
        type: db.Sequelize.INTEGER,
        allowNull: false,
        unique:"liked_user" // this will create composite key
    },
    anonymously:{
        type : db.Sequelize.BOOLEAN,
        defaultValue : false,
        comment :  "( True : user wants to be anonymous )"
    }
}

All you need to do is use unique:"liked_user" , where liked_user is name of key , just for identification , and that should be same for the fields you want to make composite.

Association :

ItemLikes.belongsTo(Item,{foreignKey: 'item_id'});
Item.hasMany(ItemLikes,{foreignKey:'item_id'});

ItemLikes.belongsTo(User,{ foreignKey : 'user_id'});
User.hasMany(ItemLikes, { foreignKey: 'user_id'});

Upvotes: 3

Related Questions