Sequelize.ts – "is not associated to"

Advertisements

I am using postgres
I want to create self-reference many-to-many association for the User model as User can follow many users and can be followed by many users
but I got this error User is not associated to Follow
this is User model

class UserModel extends Model implements User {
  readonly id!: number;
  email!: string;
  password!: string;
  readonly createdAt!: Date;
  readonly updatedAt!: Date;
}

UserModel.init(
  {
    id: { type: DataTypes.INTEGER, autoIncrement: true, primaryKey: true },
    email: { type: DataTypes.STRING, unique: true, allowNull: false, validate: { isEmail: true } },
    password: {
      type: DataTypes.STRING,
      allowNull: false,
    },
  },
  { timestamps: true, sequelize, modelName: 'User', freezeTableName: true }
);

UserModel.belongsToMany(UserModel, {
  as: 'following',
  through: FollowModel,
  foreignKey: 'userId',
});

UserModel.belongsToMany(UserModel, {
  as: 'follower',
  through: FollowModel,
  foreignKey: 'followId',
});

UserModel.sync();
export default UserModel;

this is Follow model

class FollowModel extends Model implements Follow {
  readonly id!: number;
  userId!: number;
  followId!: number;
}

FollowModel.init(
  {
    id: { type: DataTypes.INTEGER, autoIncrement: true, primaryKey: true },
    userId: {
      type: DataTypes.INTEGER,
      references: { model: UserModel, key: 'id' },
      allowNull: false,
    },
    followId: {
      type: DataTypes.INTEGER,
      references: { model: UserModel, key: 'id' },
      allowNull: false,
    },
  },
  { sequelize, modelName: 'Follow', freezeTableName: true, timestamps: false }
);

FollowModel.sync();
export default FollowModel;

the error occures from this endpoint

export const followersList = asyncHandler(async (req, res, next) => {
  const list = await FollowModel.findAll({
    where: { followId: res.locals.userId },
    attributes: [],
    include: [
      {
        model: UserModel,
      },
    ],
  });
  res.status(200).json({ count: list.length, list: list });
});

I try to learn sequelize so please help me on understanding this error

>Solution :

You defined associations for both ends of M:N relationship for User model but you didn’t define the associations from Follow to User because you execute the query where the main model is indeed Follow and not the User:

FollowModel.belongsTo(UserModel, {
  as: 'followedUser',
  foreignKey: 'userId',
});

UserModel.belongsTo(UserModel, {
  as: 'followingUser',
  foreignKey: 'followId',
});

and of course you need to indciate the proper alias in the include option:

const list = await FollowModel.findAll({
    where: { followId: res.locals.userId },
    attributes: [],
    include: [
      {
        model: UserModel,
        as: 'followingUser'
      },
    ],
  });

Leave a ReplyCancel reply