javascript - Sequelize M:N 关联操作
问题描述
我有一个使用 postgre DB 的续集模式
export const Commune = sq.define("commune",{
codeCommune: {
type: DataTypes.STRING(5),
allowNull: false,
primaryKey: true
},
libelleCommune: {
type: DataTypes.STRING,
allowNull:false
},
actif: {
type: DataTypes.BOOLEAN,
allowNull:true
}
},{timestamps: false,modelName:"Commune"});
export const CodePostal = sq.define("codePostal",{
codePostal: {
type: DataTypes.STRING(5),
allowNull: false,
primaryKey: true
}
},{timestamps: false,modelName:"CodePostal"});
export const R_Commune_CodePostal = sq.define("R_Commune_CodePostal",{},{timestamps:false});
CodePostal.belongsToMany(Commune,{through: R_Commune_CodePostal});
Commune.belongsToMany(CodePostal,{through: R_Commune_CodePostal});
我已经成功创建了这个:
await CodePostal.create({
codePostal: "37340",
communes: [
{
codeCommune: "37002",
libelleCommune:"Ambillou",
actif: true
},
{
codeCommune:"37013",
libelleCommune: "Avrillé-les-Ponceaux",
actif: true
}
]
}, {include: Commune}).then ...
现在我想像这样列出所有数据:
CodePostal.findAll({raw:true,include:[{model: Commune},nest:true}).then ...
预期输出:
{codePostal: "37340",
communes: [
{codeCommune: "37002",libelleCommune: "Ambillou",actif: true},
{codeCommune: "37013",libelleCommune: "Avrillé-les-Ponceaux",actif: true}
]}
但我有这个:
[ { codepostal: '37340',
communes: {
codeCommune: '37002',
libelleCommune: 'Ambillou',
actif: true,
R_Commune_CodePostal: [Object] } },
{ codepostal: '37340',
communes: {
codeCommune: '37013',
libelleCommune: 'Avrillé-les-Ponceaux',
actif: true,
R_Commune_CodePostal: [Object] }
}
]
对于每个公社,sequelize 加入邮政编码,用于在每个邮政编码的数组中列出公社。
有人可以帮我实现这个结果吗?
解决方案
raw: true
将返回数据,因为 DB 在普通响应中返回。这意味着它将每个关联返回为 1 行。但是,您的预期输出将复合成 1 个数组,用于相同的codepostal
.
默认情况下(不带raw: true
),findAll
应该作为您的预期输出返回,nest: true
也不是必需的。
CodePostal.findAll({
include:[{model: Commune}]
})
此外,如果您不需要through
表中的属性,您可以添加这些选项以获得更清晰的响应。
CodePostal.findAll({
include:[{
model: Commune,
through: {
attributes: []
}
}]
})
推荐阅读
- fifo - 读取 FT2332H FIFO 数据
- python - 一次性导入所有子模块
- javascript - 使用 Nashorn 从 Java 中的 JavaScript 代码返回输出值
- django - 为什么它显示的空路径不匹配任何这些
- git - 在 git diff 中,区分删除和移动
- python-3.x - DataFrame.write.parquet() 只使用一个执行器,不扩展
- python - LSTM 文本生成 Input_shape
- python - 如何从用户输入中对文本文件执行搜索
- database - 手动更新 ID 列会损害数据库吗?
- python - 洛书魔方总是返回假