如何为sequelize模型添加常用属性?

时间:2017-11-29 07:12:28

标签: express sequelize.js feathersjs

我试图在sequlize中使用钩子为模型添加常用属性, 我已经定义了一个全局钩子,如下所示,

module.exports = function (app) {
  const sequelizeClient = app.get('sequelizeClient');
  sequelizeClient.addHook('beforeDefine', (attributes) => {
    var defaultAttributes = {
      id: {
        type: Sequelize.INTEGER,
        autoIncrement: true,
        primaryKey: true
      },
      createdBy: {
        type: Sequelize.INTEGER,
      },
      updatedBy: {
        type: Sequelize.INTEGER,
      },
      deletedBy: {
        type: Sequelize.INTEGER,
      }
    };
    Object.assign(attributes, defaultAttributes);
    //return attributes;
  });
};

但即使钩子被触发,属性仍未添加到模型中。我想从这里https://github.com/sequelize/sequelize/issues/4383添加常用属性的钩子。我在这做错了什么?或者有更好的方法来添加常见属性吗?

请注意我使用mysql作为后端数据库。我正在使用的续集模型如下。

module.exports = function (app) {
  const sequelizeClient = app.get('sequelizeClient');
  const person = sequelizeClient.define('person', {
    name: {
      type: DataTypes.STRING,
      allowNull: false
    }
  }, {
    hooks: {
      beforeCount(options) {
        options.raw = true;
      }
    }
  });

  person.associate = function (models) { // eslint-disable-line no-unused-vars
    // Define associations here
    // See http://docs.sequelizejs.com/en/latest/docs/associations/
  };

  return person;
};

0 个答案:

没有答案