mysql - 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
在发出请求之前检查,但仍然想知道这个可能的根快捷方式
有谁知道?
解决方案
找到了一个我很高兴的解决方案:
搜索把我带到了这里,这让我为此创建了一个模型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);
}
};
推荐阅读
- bloomberg - Can we use BLPAPI remotely?
- spring-boot - Azure active directory integration angular + adal+ spring boot
- r - R滚动连接两个data.tables,连接时有误差
- nginx - Nginx does not serve css and js from upstream servers
- reactjs - Firebase + react : read document in auth state changed and add it to context
- c++ - 类型特征是否可以限制为不接受其他类型特征作为参数?
- javascript - 添加动态按钮以显示弹出窗口以链接条目
- javascript - XMLHttpRequest() 在 Opera mini 中不起作用
- ckfinder - ckfinder ImagePreview vs Thubnail
- javascript - 搜索大量长文本时正则表达式不佳