Reputation: 399
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,
These are the sources I took for reference
Upvotes: 1
Views: 1061
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