Sequelize创建BelongsToMany的元素

时间:2018-06-16 09:06:27

标签: javascript node.js sequelize.js

所以我一直在使用Sequelize,我很难通过这样的创建来创建连接表的元素:

db.Food.create({
    name: "Test",
    description: "Test",
    calories: 1,
    created_by: 1,
    local_id: 1,
    nutrients: [{"name":"Carbs","amount":"0"},{"name":"Fat","amount":"0"},{"name":"Protein","amount":"0"}]
}, {
    include: [{
        model: db.Nutrient,
        as: 'nutrients'
    }]
});

我有两个模型,即食物和营养素,以及一个名为FoodNutrient的连接表:

食品

module.exports = function (sequelize, DataTypes) {
    var Food = sequelize.define('Food', {
        id: {
            type: DataTypes.INTEGER,
            primaryKey: true,
            autoIncrement: true,
        },
        local_id: DataTypes.INTEGER,
        name: DataTypes.STRING,
        description: DataTypes.STRING,
        calories: DataTypes.FLOAT
    });

    Food.associate = function (models) {
        Food.belongsTo(models.UserProfile, {
            foreignKey: 'created_by'
        });
        Food.belongsToMany(models.Nutrient, {
            through: 'FoodNutrient',
            as: 'nutrients',
            foreignKey: 'food'
        });
        Food.belongsToMany(models.ServingSize, {
            through: 'FoodServingSize',
            foreignKey: 'food'
        });
    };

    return Food;
};

营养素:

module.exports = function (sequelize, DataTypes) {
    var Nutrient = sequelize.define('Nutrient', {
        name: {
            type: DataTypes.STRING,
                primaryKey: true
        }
    }, {
        timestamps: false
    });

    Nutrient.associate = function (models) {
        Nutrient.belongsToMany(models.Food, {
            through: 'FoodNutrient',
            foreignKey: 'nutrient'
        });
    };

    return Nutrient;
};

加入表FoodNutrient:

module.exports = function (sequelize, DataTypes) {
    var FoodNutrient = sequelize.define('FoodNutrient', {
        id: {
            type: DataTypes.INTEGER,
            primaryKey: true,
            autoIncrement: true,
        },
        amount: DataTypes.FLOAT,
    });

    return FoodNutrient;
};

甚至可以实现这样的目标吗?所有的文档都说是关于hasMany的关系,所以我对belongsToMany不太确定。谢谢!

0 个答案:

没有答案