Skip to content

Trying to increment value with Model Class generates wrong SQL #10411

Closed

Description

@prionkor

Looking at the increment method example in the documentations it doesn't look like the increment have to run on an instance (because you can add where props on option).

Currently I am trying to run increment on the model class itself (see example).

What are you doing?

Trying to increment a field using Model.

hooks: {
      beforeCreate: hit => {
        sequelize.models.Link.increment({
          hitCount: 1
        }, {
          silent: true,
          where: {
            id: hit.linkId
          }
        })
      },
    }

What do you expect to happen?

Increase the field by one

What is actually happening?

SQL Error: Unknown column '0' in 'field list'.

The query is almost correct but sequelize adds model fields into the query.

UPDATE `links` SET `hitCount`=`hitCount`+ 1,`0`='id',`1`='name',`2`='originalUrl',`3`='code',`4`='type',`5`='userId',`6`='opengraph',`7`='shortUrl',`8`='createdAt',`9`='updatedAt' WHERE `id` = 40

Dialect: mysql
Dialect version: 1.6.4
Database version: MySQL 5.7.25-0ubuntu0.18.04.2 - (Ubuntu)
Sequelize version: 4.42.0
Tested with latest release: YES (4.42.0)

Similar: #9572

Activity

  1. sushantdhiman commented on Feb 16, 2019

    @sushantdhiman
    Contributor

    Are you using any scopes?

  2. prionkor commented on Feb 16, 2019

    @prionkor
    Author

    No, I have added my full model code below.

    
    'use strict';
    
    module.exports = (sequelize, DataTypes) => {
      const Hit = sequelize.define('Hit', {
        ip: DataTypes.STRING,
        userAgent: DataTypes.STRING,
        linkId: {
          type: DataTypes.INTEGER,
          allowNull: false
        },
        datetime: DataTypes.DATE
      }, {
        tableName: 'hits',
        timestamps: false,
        hooks: {
          beforeCreate: hit => {
            /*sequelize.models.Link.increment({
              hitCount: 1
            }, {
              silent: true,
              where: {
                id: hit.linkId
              }
            })*/
            const query = "UPDATE `links` SET `hitCount`=`hitCount`+ 1 WHERE `id` = " + parseInt(hit.linkId, 10);
            sequelize.query(query);
          },
        }
      });
      
      Hit.associate = function(models) {
        // associations can be defined here
        Hit.belongsTo(models.Link, {
          foreignKey: 'linkId'
        })
      };
      
      return Hit;
    };
    
    
  3. sushantdhiman commented on Feb 17, 2019

    @sushantdhiman
    Contributor

    Problem is with Link so please include that as well

  4. prionkor commented on Feb 17, 2019

    @prionkor
    Author

    Hello, find the Link model below

    
    'use strict';
    
    const moment = require('moment');
    
    module.exports = (sequelize, DataTypes) => {
      const Link = sequelize.define('Link', {
        name: DataTypes.STRING,
        originalUrl: DataTypes.STRING,
        code: DataTypes.STRING,
        type: DataTypes.STRING,
        userId: DataTypes.INTEGER,
        hitCount: DataTypes.INTEGER,
        opengraph: DataTypes.JSON,
        shortUrl: {
          type: DataTypes.VIRTUAL,
          get: function() {
            const url = new URL(this.get('originalUrl'));
            return url.protocol + '//' + process.env.SHORTLINK_HOST + '/' + this.get('code')
          }
        }
      }, {
        freezeTableName: true,
        tableName: 'links'
      });
      
      Link.createObject = (link) => Link.findOrCreate({
          where: { code : link.code },
          defaults: link,
      });
    
      Link.associate = function(models) {
        // associations can be defined here
        Link.belongsTo(models.User, {
          as: 'user',
          foreignKey: 'userId'
        });
    
        Link.belongsToMany(models.Overlay, {
          as: 'overlays',
          through: models.LinkOverlays,
          foreignKey: 'linkId',
          targetKey: 'id',
        });
    
        Link.belongsToMany(models.Tracker, {
          as: 'trackers',
          through: models.LinkTrackers,
          foreignKey: 'trackerId',
          targetKey: 'id',
        });
    
      };
    
      Link.prototype.getFriendlyCreateDate = function(){
        return moment(this.get('createdAt')).format('MMM Do, YYYY')
      }
    
      return Link;
    };
    
    
  5. lessu commented on May 7, 2019

    @lessu

    +1
    same error

  6. self-assigned this
    on Jan 21, 2020
  7. added
    type: bug
    on Jan 21, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

type: bug

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions