我正在嘗試使用 Sequelize 中的幾個模型進行查詢。我有 2 個模型,一個是Project,另一個是Specification。一個專案可以有多個規范,一個規范只能屬于一個專案。表結構為:
專案:
- 標題
- 描述
- 創建時間
- 更新時間
規格:
- 標題
- 描述
- ProjectId(專案表中的外鍵)
這是我對規范 -> 專案的關系:
Project.belongsToMany(Specification);
我用來檢索資料的函式是這樣的。基本上它獲取所有資料,包括所有可能的關聯:
// Retrieve all Projects from the database.
exports.findAll = (req, res) => {
Project.findAll({
include: [{
all: true
}]
})
.then(data => {
res.send(data);
})
.catch(err => {
res.status(500).send({
message:
err.message || "Some error occurred while retrieving projects."
});
});
};
最后,我得到的錯誤是這樣的:
{"message":"specification is not associated to project!"}
有人可以幫助我或教我如何完成查詢嗎?我一直在嘗試,但無法得到正確的結果。謝謝!
uj5u.com熱心網友回復:
如果您將您的結構描述為
一個專案可以有多個規范,一個規范只能屬于一個專案
那么它是一個通常的 1:N 關系,在這種情況下,hasMany應該使用關聯而不是belongsToMany因為belongsToMany用于指示 M:N 關系,在這種情況下,您將需要一個連接表/模型。也就是說你只需要更換
Project.belongsToMany(Specification);
和
Project.hasMany(Specification, { foreignKey: 'ProjectId' });
我總是更喜歡明確指出一個外鍵
uj5u.com熱心網友回復:
使用hasMany代替belongsToMany來定義關系
Project.hasMany(Specification, {
foreignKey: { name: 'ProjectId' },
targetKey: 'ProjectId',
constraints: false,
as: 'specifications',
}),
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/398167.html
標籤:mysql 节点.js sequelize.js 协会
