首页 > 解决方案 > 限制 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",
    })
}

标签: javascriptsequelize.js

解决方案


如果您希望某个用户的朋友被 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 链接。


推荐阅读