【问题标题】:sequelize access relations in models functionssequelize 模型函数中的访问关系
【发布时间】:2017-01-29 23:07:08
【问题描述】:

我的数据库“modules”和“composants”中有两个表。模块可以有许多组合物并有一个 int 属性“prix”。我想为模块创建一个伪属性“prix”,它添加了其合成物的所有属性“prix”。如何访问创建伪属性的函数内部的关联组合?

module.exports = function (sequelize, DataTypes) {
    "use strict";
    var module = sequelize.define('module', {
        id_module: {
            type: DataTypes.INTEGER.UNSIGNED,
            autoIncrement: true,
            primaryKey: true
        },
        nom: {
            type: DataTypes.STRING,
            allowNull: false
        },
        coupe: {
            type: DataTypes.STRING,
            allowNull: false
        },
        gamme: {
            type: DataTypes.STRING,
            allowNull: false
        },
        prix: {
            type     : DataTypes.INTEGER.UNSIGNED,
            allowNull: false,
            get      : function(models)  {
                var prix;
                console.log(this);
                return prix;
            }
        }
    }, {
        classMethods: {
            associate: function(models) {
                module.hasMany(models.caracteristique_module,{
                    hooks: true,
                    onDelete: 'cascade',
                    foreignKey: "id_caracteristique"
                });
                module.hasMany(models.composant, {
                    through: models.composition,
                    hooks: true,
                    onDelete: 'cascade',
                    foreignKey: "id_composant"
                })
            }
        },
        timestamps: false,
        tableName: 'modules'
    });
    return module;
};

【问题讨论】:

    标签: node.js sequelize.js models eager-loading


    【解决方案1】:

    找到了解决方案。 在模型中

    prix: {
                type     : DataTypes.INTEGER.UNSIGNED,
                allowNull: false,
                get      : function()  {
                    var prix = 0;
                    if(this.composants != undefined){
                        this.composants.forEach(function(composants){
                            prix += parseInt(composants.prix);
                        });
                    }
                    return prix;
                }
            }
    

    【讨论】:

      猜你喜欢
      • 2015-06-01
      • 2022-01-26
      • 2018-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多