Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

My self referential Sequelize model isn't creating an extra column

Tags:

sequelize.js

module.exports = (sequelize, DataTypes) => {
  const User = sequelize.define(
    "User",
    {
      username: {
        type: DataTypes.STRING,
        unique: true
      },
      firstName: {
        type: DataTypes.STRING
      },
      lastName: {
        type: DataTypes.STRING
      },
      email: {
        type: DataTypes.STRING
      },
      password: {
        type: DataTypes.STRING
      },
      lastLogin: {
        type: DataTypes.DATE
      },
      active: {
        type: DataTypes.BOOLEAN
      },
      lastName: {
        type: DataTypes.STRING
      }
    }, {
      paranoid: true,
      classMethods: {
        associate: models => {
          User.hasOne(models.User, {
            as: "createdByUser"
          })

          User.hasOne(models.User, {
            as: "updatedByUser"
          })
        }
      }
    }
  )

  return User
};

I would expect a field to be called createdByUser in the Postgres DB, but it's not there. What am I doing wrong?

like image 794
Shamoon Avatar asked Dec 07 '17 14:12

Shamoon


People also ask

What is a one to many relationship in Sequelize?

To create a One-To-Many relationship, the hasMany and belongsTo associations are used together; To create a Many-To-Many relationship, two belongsToMany calls are used together.

How do I add a foreign key in Sequelize model?

Sequelize association methods also accept an options object that you can use to configure the details of the association. For example, you can change the foreign key name on the table by adding the foreignKey property: User. hasOne(Invoice, { foreignKey: "invoice_creator", // UserId -> invoice_creator });

How do you define a model in Sequelize?

Models can be defined in two equivalent ways in Sequelize: Calling sequelize.define(modelName, attributes, options) Extending Model and calling init(attributes, options)


1 Answers

Solution was

module.exports = (sequelize, DataTypes) => {
  const User = sequelize.define(
    "User",
    {
      username: {
        type: DataTypes.STRING,
        unique: true
      },
      firstName: {
        type: DataTypes.STRING
      },
      lastName: {
        type: DataTypes.STRING
      },
      email: {
        type: DataTypes.STRING
      },
      password: {
        type: DataTypes.STRING
      },
      lastLogin: {
        type: DataTypes.DATE
      },
      active: {
        type: DataTypes.BOOLEAN
      }
    }, {
      paranoid: true
    }
  )

  User.associate = models => {
    User.hasOne(models.User, {
      as: "createdByUser"
    })

    User.hasOne(models.User, {
      as: "updatedByUser"
    })
  }

  return User
};

In the new version of Sequelize (4+), there's no need for classMethods

like image 52
Shamoon Avatar answered Oct 17 '22 04:10

Shamoon