javascript - 限制 belongsToMany 与 Sequelize 的关联
问题描述
我想知道,我怎样才能对我的 belongsToMany 关系设置一个限制。我尝试添加限制,但出现此错误:
"message": "只有 HasMany 关联支持 include.separate",
我有 2 张桌子:
| peoples (id, code)
| people-friends (fk_user_id, fk_friend_id) // fk_friend_id is an id from user
我的请求 :
await db.People.findAll({
where: {
id: parent.dataValues.id,
},
include: [
{
model: db.People,
as: "Friends",
limit: 2, // <--- LIMIT
},
],
})
人物模型:
People.associate = (models) => {
// People relations
models.People.belongsToMany(models.People, {
as: "Friends",
through: models.PeopleFriend,
foreignKey: "fk_user_id",
otherKey: "fk_friend_id",
})
}
解决方案
如果您希望某个用户的朋友被 2 个朋友限制(哪些?您必须添加一个order
选项),您可以像这样查询 PeopleFriend 包括 People 模型:
await db.PeopleFriend.findAll({
where: {
fk_user_id: parent.dataValues.id
},
limit: 2, // <--- LIMIT
order: [['Friend', 'name', 'asc']],
include: [
{
model: db.People,
as: "Friend",
},
{
model: db.People,
as: "User",
},
],
})
不要忘记将来自 PeopleFriend 的关联添加到两个 People 链接。
推荐阅读
- mysql - Mysql 结果集中的首选项
- c# - 如何在 OpenCascade 中用颜色显示侧面?
- javascript - 在没有逻辑 AND 运算符的情况下检查 If 语句中的多个真值
- wordpress - Wordpress Polylang 字符串可搜索?
- jquery - 在jquery中调整窗口大小时根据div宽度动态椭圆化文本
- html - 简单的 Bootstap 表单 m- 不能很好地整理按钮/文本对齐
- python - Python将带有数据集的字典导出到excel中的不同选项卡
- azure - 无法使用 AKS 和 ACR 拉取新映像
- sql - 使用递归查询 ORACLE 11G 查找客户之间的所有依赖关系
- c# - 如何在 c# WPF 中将 byte[] 转换为 BitmapSource