Sequelize M:N 关联操作

Sequelize M:N association manipulation

我有一个使用 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 将 return 数据作为 DB return 的简单响应。这意味着它将 return 每个关联作为 1 行。但是,对于相同的 codepostal.

,您的预期输出被复合到 1 个数组中

默认情况下(没有 raw: true),findAll 应该 return 作为您的预期输出,并且 nest: true 也不是必需的。

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

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

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