首页 > 解决方案 > 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 加入邮政编码,用于在每个邮政编码的数组中列出公社。

有人可以帮我实现这个结果吗?

标签: javascriptnode.jstypescriptsequelize.jssequelize-typescript

解决方案


raw: true将返回数据,因为 DB 在普通响应中返回。这意味着它将每个关联返回为 1 行。但是,您的预期输出将复合成 1 个数组,用于相同的codepostal.

默认情况下(不带raw: true),findAll应该作为您的预期输出返回,nest: true也不是必需的。

CodePostal.findAll({
    include:[{model: Commune}]
})

此外,如果您不需要through表中的属性,您可以添加这些选项以获得更清晰的响应。

CodePostal.findAll({
    include:[{
        model: Commune,
        through: {
            attributes: []
        }
    }]
})

推荐阅读