Sequester multiple primary keys

I have some problems with Sequelize with multiple primary keys; therefore multiple foreign keys with multiple hasMany on the same table.

Suppose I have a User

const User = sequelize.define('User', {
    id: { type: DataTypes.STRING(6), field: 'ID', primaryKey : true }
)
associate: function(models) {
        User.hasMany(models.Post, { foreignKey: 'userId' });
}

      

and I have a post under user

const Post = sequelize.define('Post', {
    id: { type: DataTypes.STRING(6), field: 'ID', primaryKey: true }, // primary key
    userId: { type: DataTypes.STRING(6), field: 'USER_ID', primaryKey: true },           // primary key
)
associate: (models) => {
        Post.belongsTo(models.User, { foreignKey: 'userId' });
        Post.hasMany(models.PostImage, { onDelete: 'CASCADE', foreignKey: 'postId' });// { key1: 'id', key2: 'userId'}
        Post.hasMany(models.PostImage, { onDelete: 'CASCADE', foreignKey: 'userId' });// { key1: 'id', key2: 'userId'}
}

      

and Post Images below the post

const PostImage = sequelize.define('PostImage', {
    postId: { type: DataTypes.STRING(6), field: 'POST_ID', primaryKey: true },
    userId: { type: DataTypes.STRING(6), field: 'USER_ID', primaryKey: true }
)
associate: (models) => {
        PostImage.belongsTo(models.Post, { foreignKey: 'postId' });
        PostImage.belongsTo(models.Post, { foreignKey: 'userId' });
}

      

Now it seems that two primary keys with two foreign keys do not work for the "include" method to use findOne or findAll.

Post.findAll({
      attributes: ['id', 'userId', 'content', 'modifyDate', 'registerDate'],
      where: {...},
      include: [{
        model: models.PostImages,
      }
)

      

It seems like only one primary key with one foreign key is related to each other for Post and Post Image table. So if I remove the relation

Post.hasMany(models.PostImage, { onDelete: 'CASCADE', foreignKey: 'userId' });// { key1: 'id', key2: 'userId'}

      

from Post to do only one foreign key with Post Image, then it will work as I expected. But this causes a problem because it only counts the Post Post Image ID, not the users, so it also displays the images of other users.

How can I use multiple primary keys with multiple foreign keys in sequelize?

+3


source to share





All Articles