将对象属性映射到多个字段

时间:2017-01-22 00:05:34

标签: sequelize.js

Sequelize.js是否有可能在映射到单独的DB列时将模型的字段映射到对象(哈希,映射等)?例如,类似于以下内容:

sequelize.define(
    'user',
    {
        ...,
        name: {
            first: {
                field: "first_name",
                type: sequelize.STRING,
                allowNull: false
            },
            middle: {
                field: "middle_name",
                type: sequelize.STRING
            },
            last: {
                field: "last_name",
                type: sequelize.STRING
            }
        },
        ...
    }
)

这可以让您执行currentUser.name.first = "Sally"之类的操作,但会映射到包含first_namemiddle_namelast_name的单独列的表格。

1 个答案:

答案 0 :(得分:1)

您可以定义一个getter方法

http://docs.sequelizejs.com/en/latest/docs/models-definition/#defining-as-part-of-the-model-options

var User = sequelize.define('user', {
  first_name: Sequelize.STRING,
  last_name: Sequelize.STRING
}, 
{
   getterMethods: {
     name: function(){ 
       return {
         first_name : this.first_name,
         last_name : this.last_name
       } 
     }
   }
});