How to SELF JOIN using Sequelize in Node
Asked Answered
Q

1

2

I'm using sequelize-cli for migrations and have researched different scenarios but there doesn't seem to be a definite solid answer as to how to self join. I want to have a join table called friendships which joins users and friends (which are essentially just users).

More specifically trying to gain an understanding about the difference between "through" and "as" in this situation.

1) This is my friendship table. Getting tripped up on the second association. I have created two columns, one being userId, and one being friendId. I am hoping to be able to have this table linked to 2 users, one in each table, with one column aliased as "friendId".

```

'use strict';
module.exports = function(sequelize, DataTypes) {
  var friendship = sequelize.define('friendship', {
    userId: DataTypes.INTEGER,
    friendId: DataTypes.INTEGER
  }, {
    classMethods: {
      associate: function(models) {
        friendship.belongsTo(models.user);
        friendship.belongsTo(models.user { as: "friend" });
      }
    }
  });
  return friendship;
};

```

2) This is my user model. Again, specifically in the associations object is where I am not clear. The goal here is to be able to call user.friends and have all instances of that user's friends show up. Not certain I am using the "through" and "as" keywords right.

```

'use strict';
module.exports = function(sequelize, DataTypes) {
  var user = sequelize.define('user', {
    username: DataTypes.STRING,
    password: DataTypes.STRING,
    email: DataTypes.STRING
  }, {
    classMethods: {
      associate: function(models) {
        user.hasMany(models.friendship);
        user.hasMany(models.user { as: "friends", through: models.friendship });
      }
    }
  });
  return user;
};

```

Quadrisect answered 12/9, 2016 at 17:6 Comment(0)
G
2

There is many-to-many relation, it should go through belongsToMany associations, no more relation is needed. There is no need even to define friends table, sequelize will create table automatically

'use strict';
module.exports = function(sequelize, DataTypes) {
      var user = sequelize.define('user', {
        username: DataTypes.STRING,
        password: DataTypes.STRING,
        email: DataTypes.STRING
      }, {
        classMethods: {
          associate: function(models) {
            user.belongsToMany(models.user, {
               as: "friends", 
               through: "friendship", 
               foreignKey: "userId", 
               otherKey: "friendId"
            });
          }
        }
      });
      return user;
};
Guinness answered 13/9, 2016 at 9:13 Comment(2)
Thanks, I can now access user.getFriends().then(function(friends))........ but it's returning an empty array here in my friendships controller. Here are the first 6 or so lines of that controller. ``` var friendshipController = { index: function(req, res) { user.findById(3).then(function(user) { user.getFriends().then(function(friends) { console.log(friends); }) }) ``` console logging friends returns an empty array, however when I look at the friendship table, I see a friendship that I seeded with userId 3 and userId 1..Quadrisect
try to log sql query that executes. .getFriends({logging: console.log}) check is query okGuinness

© 2022 - 2024 — McMap. All rights reserved.