【问题标题】:Sequelize M:N association manipulationSequelize M:N 关联操作
【发布时间】:2021-11-16 06:29:32
【问题描述】:

我有一个使用 postgre DB 的 sequelize 架构

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

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

【问题讨论】:

    标签: javascript node.js typescript sequelize.js sequelize-typescript


    【解决方案1】:

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

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

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

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

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

    【讨论】:

    • 非常感谢!我只是将结果处理成一个 forEach 循环以将结果作为 JSON 对象。
    • 将 sequelize 实例转换为用于 findAll 的 JSON 对象,请查看此处。在不变性方面,map 通常比 forEach 更好。 stackoverflow.com/a/21982117/2956135
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-11
    • 1970-01-01
    • 1970-01-01
    • 2017-08-15
    • 2013-10-05
    • 2018-12-09
    相关资源
    最近更新 更多