Brad
Brad

Reputation: 163602

Sequelize self association creates extra column

I have the following model defined with Sequelize:

module.exports = function (sequelize, DataTypes) {
  var Genre = sequelize.define('Genre', {
    name: {
      type: DataTypes.STRING,
      allowNull: false
    }
  }, {
    classMethods: {
      associate: function (models) {
        Genre.hasMany(models.Genre, {as: 'subGenre'});
        Genre.belongsTo(models.Genre, {as: 'parentGenre'});
      }
    }
  });

  return Genre;
}

The idea is that there will be parent genres, and each may have several sub-genres. When I run sync(), the table is created fine, but there is an extra column (GenreId) that I can't quite explain:

"id";"integer";
"name";"character varying";255
"createdAt";"timestamp with time zone";
"updatedAt";"timestamp with time zone";
"GenreId";"integer";
"parentGenreId";"integer";

The sensible way to interpret the model is to only have a parentGenreId column, but I am not sure how to define that bi-directional relationship (genre may have parent, genre may have many children) with only one column being added.

How can I rework the model to allow the relationship to be defined correctly?

Upvotes: 0

Views: 3366

Answers (1)

Dan Rocha
Dan Rocha

Reputation: 635

I think you could use through (not tested)

module.exports = function (sequelize, DataTypes) {
  var Genre = sequelize.define('Genre', {
    name: {
      type: DataTypes.STRING,
      allowNull: false
    }
  }, {
      classMethods: {
        associate: function (models) {
          Genre.hasMany(models.Genre, {as: 'children', foreignKey: 'ParentId'});
          Genre.belongsTo(models.Genre, {as: 'parent', foreignKey: 'ParentId'});
        }
      }
});

  return Genre;
}

So you could have Genre#getChilren and Genre#getParent

EDIT: Due to @mick-hansen, through applies for belongsToMany, not useful for this case. My fault. Corrected using his recommendation

Upvotes: 2

Related Questions