Sequelize association table组

Sequelize association table group

我有两个 tables medforms 和类别,每个 medform 可以有多个类别。对于多个类别,我建立了另一个关联 table medform_categories.

'use strict';
 const {
 Model
  } = require('sequelize');
 module.exports = (sequelize, DataTypes) => {
 class MedForm extends Model {
    /**
     * Helper method for defining associations.
     * This method is not a part of Sequelize lifecycle.
     * The `models/index` file will call this method automatically.
     */
    static associate(models) {
        // define association here
    }
};
MedForm.init({
    med_id: {
        type: DataTypes.INTEGER,
        primaryKey: true,
        autoIncrement: true
    },
    med_name: {
        type: DataTypes.STRING,
        allowNull: false
    },
}, {
    sequelize,
    modelName: 'medforms',
});
MedForm.associate = function (models) {
    MedForm.hasMany(models.medforms_category, {
        foreignKey: 'med_id',
        as: 'medform'
    });
};
return MedForm;
};

类别table架构:

'use strict';
 const {
 Model
 } = require('sequelize');
  module.exports = (sequelize, DataTypes) => {
  class Category extends Model {
    static associate(models) {
    }
};
Category.init({
    category_id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: DataTypes.INTEGER
    },
    category_name: {
        type: DataTypes.STRING,
    },
    }, {
    sequelize,
    modelName: 'categories',
});
Category.associate = function (models) {
    Category.hasMany(models.medforms_category, {
        foreignKey: 'category_id',
        as: 'category'
    });
};
return Category;
};

最后是协会tablemedform_category

    'use strict';
const {
    Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
    class Medform_categories extends Model {
              static associate(models) {
                  }
    };
    Medform_categories.init({
        medform_category_id: {
            type: DataTypes.INTEGER,
            primaryKey: true,
            autoIncrement: true
        },
        category_id: {
            type: DataTypes.INTEGER,
            references: {
                model: 'categories',
                key: 'category_id'
            },
            onUpdate: 'CASCADE',
            onDelete: 'CASCADE'
        },
        med_id: {
            type: DataTypes.INTEGER,
            allowNull: false,
            references: {
                model: 'medforms',
                key: 'med_id'
            },
            onUpdate: 'CASCADE',
            onDelete: 'CASCADE'
        },
    }, {
        sequelize,
        modelName: 'medform_categories',
    });
    Medform_categories.associate = function (models) {
        Medform_categories.belongsTo(models.medforms, {
            foreignKey: 'med_id',
            as: 'medform'
        });
        Medform_categories.belongsTo(models.categories, {
            foreignKey: 'category_id',
            as: 'category'
        });
    };
    return Medform_categories;
};

现在我想要这样的数据:

"category": [
            {
                "category_id": 1,
                "category_name": "cat1",
                "medforms": {
                    "med_id": 1,
                    "med_name": "Mobilfunk 1",
                    "med_fullname": "Mobilfunk 1",
                },
                {
                    "med_id": 2,
                    "med_name": "Mobilfunk 2",
                    "med_fullname": "Mobilfunk 2",
                }
            },
            {
                "category_id": 2,
                "category_name": "cat2",
                "medforms": {
                    "med_id": 1,
                    "med_name": "Mobilfunk 1",
                    "med_fullname": "Mobilfunk 1",
                },
                {
                    "med_id": 3,
                    "med_name": "Mobilfunk 3",
                    "med_fullname": "Mobilfunk 3",
                }
            },
            ]
        

can some one please help me here? what I should do here? Inside the controller to fetch data like mentioned above?

const db = require("../models");
const Categories = db.categories; // tables db instance
// Retrieve all objects (with include)
exports.getAllCategories = (req, res) => {
    Categories.findAll({
        include: [
            {
                model: db.medforms_category,
                as: 'category',
                include: [
                    {
                        model: db.medforms,
                        as: 'medform',
                    }]
            },
        ],
    })
        .then(data => {
            res.send(data);
        })
        .catch(err => {
            res.status(500).send({
                message:
                    err.message || "Some error occurred while retrieving all data."
            });
        });
};

如果你有一个N:N关系,你不一定需要有一个Model来表示这个table。

// Medforms
// ...

static associate(models) {
    this.belongsToMany(models.categories, { through: 'medform_categories' });
}

// Categories
// ...
static associate(models) {
    this.belongsToMany(models.medforms, { through: 'medform_categories' });
}

// Query will be something like
const categories = await Categories.findAll({
    where: {...},
    include: ['medforms']
})

const medforms = await Medforms.findAll({
    where: {...},
    include: ['categories']
})