Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize join table through foreign keys not created

I am trying to create a user > friend relationship in sequelize. Therefore, I created a user model and a belongsToMany relationship through a join-table called friends. It created the table but the foreignKeys userId and friendId are not created. I would be happy if someone could help me out.

User model:

var User = sequelize.define('user', {
    id: {
      type: Sequelize.INTEGER,
      autoIncrement: true,
      primaryKey: true
    },
    emailaddress: {
      type: Sequelize.STRING
    },
    firstname: {
      type: Sequelize.STRING
    },
    lastname: {
      type: Sequelize.STRING
    },
    description: {
      type: Sequelize.STRING
    },
    password: {
      type: Sequelize.STRING
    }
  }, {
    freezeTableName: true, 
    classMethods: {
      associate: function (models) {
        User.belongsToMany(models.user, {
          as: "user",
          through: "friend"
        });
        User.belongsToMany(models.user, {
          as: "friend",
          through: "friend"
        });
        User.sync({
            force: true
          })
      }
    }
  });

friend model

var Friend = sequelize.define('friend', {
    // userId: DataTypes.INTEGER,
    // friendId: DataTypes.INTEGER,
    status: {
      type: DataTypes.BOOLEAN,
      defaultValue: 0
    }
  }, {
    freezeTableName: true,
    classMethods: {
      associate: function (models) {
        Friend.sync()
      }
    }
  });

This generates the following field in the friend table:

id status createdAt updatedAt

I would like the following fields:

id status userId friendId createdAt updatedAt

package.json > "sequelize": "^3.17.1",

like image 754
Bram Avatar asked Mar 04 '26 09:03

Bram


2 Answers

You can set otherKey and foreignKey to a sequelize associations. I think you should try this:

User.belongsToMany(models.user, {
    as: "friends",
    through: "friend",
    otherKey: 'userId',
    foreignKey: 'friendId'
});

Sorry I can't try it right now, but I hope, it helps you.

like image 187
Gergo Avatar answered Mar 07 '26 05:03

Gergo


After some debugging I found out that the problem was that I called Table.sync on initializing every table instead of doing it just once when all tables are defined (see the example code in the sequelize express example on github: https://github.com/sequelize/express-example). This corrupted the table creation process.

like image 37
Bram Avatar answered Mar 07 '26 04:03

Bram