Skip to content

attributes not respected for fields with getter  #5948

Closed

Description

@ro70

What you are doing?

There's a 1:n association between model A and model B. I'd like to find one A entity with all associated B entities. I only want to get a few selected attributes. All fields with a virtual getter are sent with the included model. The attributes don't seem to be respected for fields with a getter.

models.A.findOne({
      where: {id: 5},
      attributes: ['id'],
      include: [{
        model: models.B,
        attributes: ['id']
      }]
    })
    .then(function(r) {
      ...
    })
var A = sequelize.define("A", {
    text: DataTypes.STRING
  }, {
    classMethods: {
      associate: function(models) {
        A.hasMany(models.B, {foreignKey: 'a_id'})
      }
    }
  });

var B = sequelize.define("B", {
    text: {
      type: DataTypes.STRING,
      get: function() {
        return this._toArr(this.getDataValue('text'))
      },
    priority: DataTypes.INTEGER(1).UNSIGNED
    }
  }, {
    classMethods: {
      associate: function(models) {
        B.belongsTo(models.A, {foreignKey: 'a_id', foreignKeyConstraint: true})
      }
    },
    instanceMethods: {
      // convert string to array
      _toArr: function(s) {
        if(s) {
          var arr = _.split(s, ';')
          return arr
        }
        return []
      }
    }
  });

What do you expect to happen?

{ id: 5,
     B:
      [ { id: 1 },
        { id: 2 } ]
}

What is actually happening?

{ id: 5,
     B:
      [ { id: 1, text: [...] },
        { id: 2, text: [...] } ]
}

Activity

  1. mickhansen commented on May 24, 2016

    @mickhansen
    Contributor
  2. zuck commented on Sep 5, 2016

    @zuck

    @mickhansen This issue seems to cover more cases than #5566, so maybe this should be left open instead.

  3. hanego commented on Sep 7, 2016

    @hanego

    I don't know if it can help some people but I found a dirty solution for this by applying get({plain:true}) to my object like this:

                var array = [];
                for (var i = 0; i < instances.length; i++) {
                    array.push(instances[i].get({
                        plain: true
                    }));
                }
    
                res.json({
                    results: array
                });
    

    And it worked for me (a bit overkill solution I guess...)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions