LiuQiangsheng
LiuQiangsheng

Reputation: 55

Sequelize attribute does not work

When I made a Query is like below.

models.A.findAndCountAll(
  {
    include: [
      models: models.B,
      as: 'C',
      attribute: ['a']
    ],
    order
    offset
    limit  
  }
)

A hasOne B as 'C' B belongsTo A

There are 'a', 'b', 'c' fields in B and I just want to retrieve 'a'. So I add the attribute option.

But when I execute this query I get all the field defined in B. It's really terrible when there are many fields in B.

Did I do something wrong?

Sorry for my poor English.

Upvotes: 0

Views: 2176

Answers (1)

doublesharp
doublesharp

Reputation: 27599

The query syntax for Sequelize requires you to pass in either a Model, and array of Models, or an array of object definitions (as, attributes, etc). You are using square brackets ([]) for an array but treating the value as an object, so the attribute definition isn't included. Use curly braces ({}) to define the Model attributes to include. The object key for the model should be model, not models as in your example, and you are missing commas for the last parameters.

models.A.findAndCountAll(
  {
    include: [ 
      {  // <-- brace here
        model: models.B, // "models" key should be "model"
        as: 'C',
        attributes: ['a']
      }, // <-- brace here
    ],
    order,
    offset,
    limit,
  }
);

Upvotes: 2

Related Questions