HenonoaH
HenonoaH

Reputation: 399

Sequelize getting unknown column in belongsToMany association

I have three models Channel, ChannelUser & Conversation. I'm trying to get all conversations from the Channel model but I ran into an unknown column issue (SequelizeDatabaseError: Unknown column 'Conversations->ChannelUser.ConversationId' in 'field list').

These are the association I'm using in models,

Channel Model

    static init(sequelize, DataTypes) {
        return super.init(
            {
                name: DataTypes.STRING(),
            },
            {
                sequelize,
                freezeTableName: true
            }
        );
    }

    static associate(models) {
        this.channelUser = this.hasMany(models.channelUser, { foreignKey: 'channelId' });
        this.conversation = this.belongsToMany(models.conversation, {
            through: {
                model: models.channelUser
            },
            foreignKey: 'channelId',
            otherKey: 'id'
        });
    }

ChannelUser Model

    static init(sequelize, DataTypes) {
        return super.init(
            {
            },
            {
                sequelize,
                freezeTableName: true
            }
        );
    }

    static associate(models) {
        this.channel = this.belongsTo(models.channel, { foreignKey: 'channelId' });
        this.user = this.belongsTo(models.user, { foreignKey: 'userId' });
        this.conversation = this.hasMany(models.conversation, {
            foreignKey: 'channelUserId',
        });
    }

Conversation Model

    static init(sequelize, DataTypes) {
        return super.init(
            {
                message: DataTypes.TEXT()
            },
            {
                sequelize,
                freezeTableName: true
            }
        );
    }

    static associate(models) {
        this.channelUser = this.belongsTo(models.channelUser, { foreignKey: 'channelUserId' });
    }

I'm also sharing the ER diagram for reference,

ER diagram reference

These are the sources I took for reference

  1. Sequelize Find belongsToMany Association
  2. Sequelize findAll with belongsToMany association
  3. How to disambiguate between multiple associations between the same models in Sequelize
  4. https://sequelize.org/master/class/lib/associations/belongs-to-many.js~BelongsToMany.html
  5. https://sequelize.readthedocs.io/en/v3/api/associations/belongs-to-many/

Upvotes: 1

Views: 1061

Answers (1)

Greg Belyea
Greg Belyea

Reputation: 878

Well the way I see it is, you have a bad belongsToMany join in here... that assumes many to many and you don’t have that... The channel user table should only join channel and user... the you should have a user conversation join table that is many to many... and a channel itself would just be a hasMany on conversation since a conversation can actually only belong to one channel.

Upvotes: 1

Related Questions