[英]Sequelize error with join table: DatabaseError [SequelizeDatabaseError]: column does not exist
我正在嘗試運行以下代碼塊,由於某種原因,查詢嘗試將其插入標記為"users->user_group"."userUuid"的列中,盡管事實上我沒有在項目(通過不在代碼庫中搜索),還檢查 pg-admin 中的列(使用 PostgreSQL), user_group 表中的兩個列都是user_uuid和group_uuid ,這兩個列也都經過驗證和正確填充。
const result = await group.findAll({
include: user,
});
Postman 正文返回以下錯誤“提示”:“也許您的意思是引用列“users->user_group.user_uuid”。”,
我有 3 個模型用戶、組和 user_group。 這些關系已根據文檔和無數其他文章和視頻進行定義。
用戶 model
module.exports = (sequelize, DataTypes) => {
const user = sequelize.define(
"user",
{
uuid: {
type: DataTypes.STRING,
primaryKey: true,
allowNull: false,
unique: true,
},
username: {
type: DataTypes.STRING,
unique: true,
allowNull: false,
},
{
freezeTableName: true,
}
);
user.associate = (models) => {
user.belongsToMany(models.group, {
// as: "userUuid",
through: models.user_group,
foreignKey: "user_uuid",
});
};
return user;
};
組 model
module.exports = (sequelize, DataTypes) => {
const group = sequelize.define(
"group",
{
uuid: {
type: DataTypes.STRING,
primaryKey: true,
allowNull: false,
unique: true,
},
title: {
type: DataTypes.STRING,
unique: true,
allowNull: false,
},
},
{
freezeTableName: true,
}
);
group.associate = (models) => {
group.belongsToMany(models.user, {
// as: "groupUuid",
through: models.user_group,
foreignKey: "group_uuid",
});
};
return group;
};
用戶組 model
module.exports = (sequelize, DataTypes) => {
const user_group = sequelize.define(
"user_group",
{
uuid: {
type: DataTypes.STRING,
primaryKey: true,
allowNull: false,
unique: true,
},
user_uuid: {
type: DataTypes.STRING,
allowNull: false,
references: {
model: "user",
key: "uuid",
},
},
group_uuid: {
type: DataTypes.STRING,
allowNull: false,
references: {
model: "group",
key: "uuid",
},
},
author: {
type: DataTypes.STRING,
unique: true,
allowNull: true,
},
},
{
freezeTableName: true,
}
);
user_group.associate = (models) => {
user_group.belongsTo(models.user, {
foreignKey: "user_uuid",
});
user_group.belongsTo(models.group, {
foreignKey: "group_uuid",
});
};
return user_group;
};
非常感謝任何幫助,謝謝!
您應該在belongsToMany
中指示otherKey
選項和foreignKey
以指示另一個 model 上的外鍵列,否則您最終會得到另一個鍵的默認名稱,見下文:
連接表中外鍵的名稱(表示目標模型)或表示另一列的類型定義的 object(參見 Sequelize.define 的語法)。 使用 object 時,可以添加 name 屬性來設置列的名稱。 默認為目標名稱 + 目標主鍵(您的情況:
user
+uuid
)
group.belongsToMany(models.user, {
// as: "groupUuid",
through: models.user_group,
foreignKey: "group_uuid",
otherKey: "user_uuid"
});
const result = await group.findAll({
include: {user},
});
你應該像這樣創建。 因為你錯過了這個{}。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.