为了账号安全,请及时绑定邮箱和手机立即绑定

belongsToMany 与 Sequelize 关联的限制

belongsToMany 与 Sequelize 关联的限制

函数式编程 2022-12-08 15:31:09
我想知道,如何限制我的 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",    })}
查看完整描述

1 回答

?
哈士奇WWW

TA贡献1799条经验 获得超6个赞

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


查看完整回答
反对 回复 2022-12-08
  • 1 回答
  • 0 关注
  • 63 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信