Sequelize 在 belongsToMany 关联中获取未知列
Sequelize getting unknown column in belongsToMany association
我有三个模型 Channel
、ChannelUser
和 Conversation
。我正在尝试从 Channel
模型中获取所有对话,但我 运行 进入未知列问题 (SequelizeDatabaseError: Unknown column 'Conversations->ChannelUser.ConversationId' in 'field list') .
这些是我在模型中使用的关联,
频道模型
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'
});
}
频道用户模型
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',
});
}
对话模型
static init(sequelize, DataTypes) {
return super.init(
{
message: DataTypes.TEXT()
},
{
sequelize,
freezeTableName: true
}
);
}
static associate(models) {
this.channelUser = this.belongsTo(models.channelUser, { foreignKey: 'channelUserId' });
}
我也分享ER图供参考,
这些是我参考的资料
好吧,我的看法是,你有一个不好的 belongsToMany 加入这里......假设多对多而你没有......频道用户 table 应该只加入频道和用户...您应该有一个多对多的用户对话加入 table...并且频道本身只是对话中的 hasMany,因为对话实际上只能属于一个频道。
我有三个模型 Channel
、ChannelUser
和 Conversation
。我正在尝试从 Channel
模型中获取所有对话,但我 运行 进入未知列问题 (SequelizeDatabaseError: Unknown column 'Conversations->ChannelUser.ConversationId' in 'field list') .
这些是我在模型中使用的关联,
频道模型
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'
});
}
频道用户模型
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',
});
}
对话模型
static init(sequelize, DataTypes) {
return super.init(
{
message: DataTypes.TEXT()
},
{
sequelize,
freezeTableName: true
}
);
}
static associate(models) {
this.channelUser = this.belongsTo(models.channelUser, { foreignKey: 'channelUserId' });
}
我也分享ER图供参考,
这些是我参考的资料
好吧,我的看法是,你有一个不好的 belongsToMany 加入这里......假设多对多而你没有......频道用户 table 应该只加入频道和用户...您应该有一个多对多的用户对话加入 table...并且频道本身只是对话中的 hasMany,因为对话实际上只能属于一个频道。