sequelize: model::build is not being affected from scopes.

What are you doing?

model.js

module.exports = function (sequelize, DataTypes) {
  const model = sequelize.define('topic', {
    id: {
      primaryKey: true,
      autoIncrement: true,
      type: DataTypes.INTEGER(11).UNSIGNED,
    },
    subject: { // indexing maybe?
      type: DataTypes.STRING(255),
      allowNull: false,
      required: true,
    },
    creatorId: { // references to user.id
      type: DataTypes.INTEGER(11).UNSIGNED,
      required: true,
      allowNull: false,
    },
  });

  /* class methods */

  model.loadScopes = function (models) {
    this.addScope('withContent', {
      include: [{
        model: models.Content,
        required: false,
      }],
    });

    this.addScope('withUser', {
      include: [{
        model: models.User,
        as: 'author',
        required: false,
        attributes: ['id', 'firstname', 'lastname'],
      }],
    });
  };

  model.associate = models => {
    model.belongsTo(models.User, { as: 'author', foreignKey: 'creatorId' });
    model.hasOne(models.Content);
  };

  model.getFullTopic = function (params) {
    return this.scope('withContent', 'withUser').findOne({ where: { id: params.id } }); // works fine.
  };

  model.buildTopic = function (params) {
    return this.scope('withContent', 'withUser').build(params); // scopes are not being applied.
    // return this.build(params, { include: [{ ... }] }); // this way it works.
  };

  /* instance methods */

  model.prototype.createTopic = function () {
    return this.save();
  };

  return model;
};

index.js

const topic = Model.buildTopic({ subject: 'test', content: { data: 'test data' } });
topic.createTopic(); // <-- does not save content, but it does save if I have `include` instead of scope in `buildTopic` method.

Output

Executing (default): INSERT INTO `topics` (`id`,`subject`,`creatorId`,`createdAt`,`updatedAt`) VALUES (DEFAULT,'abc',1,'2018-11-19 14:35:41','2018-11-19 14:35:41');

What do you expect to happen?

I was expecting this to save the content alongside with the topic.

What is actually happening?

It is not saving content. It is saving only topic without content when I have scopes included. If I remove scopes and add include property instead, it does save.

Dialect: mysql Dialect version: 1.6.4 Database version: 8.0.1 Sequelize version: 4.41.1 Tested with latest release: 4.41.2

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Comments: 16 (6 by maintainers)

Most upvoted comments

Scopes are used for finder functions, mainly as access control. In methods like this you can pass options.include