首页 > 解决方案 > sequelize belongstomany 禁用相同的 id

问题描述

在文档中挖掘了一段时间,找不到这个选项。

场景:

User.belongsToMany(User, {
  as: 'following',
  through: 'follows',
  foreignKey: 'follower_id',
  otherKey: 'followed_id',
  // disableSameId: true <--- the kind of option I'm looking for
});

在这个场景中,我正在寻找的行为是不允许用户跟随自己。

目前我的实现很明显,id1 !== id2在发出请求之前检查,但仍然想知道这个可能的根快捷方式

有谁知道?

标签: mysqlsequelize.js

解决方案


找到了一个我很高兴的解决方案:

搜索把我带到了这里,这让我为此创建了一个模型rel-table

使用自定义validator就可以了。

return sequelize.define('Follows',
{},
{
  timestamps: true,
  paranoid: false,
  underscored: true,
  freezeTableName: true,
  tableName: 'follows',
  validate: {
    IdsShouldNotMatch() {
      compare(this, 'Cannot follow yourself');
    }
  }
});


// model_helpers/compare.js
module.exports = (that, error) => {
  let condition = Object.values(that.dataValues)
    .map(v => Number(v))
    .reduce((a, b) => a - b);
  if (!condition) {
    throw new Error(error);
  }
};

推荐阅读