限制与 Sequelize 的belongsToMany 关联 [英] Limit on belongsToMany association with Sequelize

查看:134
本文介绍了限制与 Sequelize 的belongsToMany 关联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道,如何对我的belongsToMany 关系设置限制.我尝试添加限制,但出现此错误:

I would like to know, how can I set a limit on my belongsToMany relations. I try to add limit, but I have this error :

"message": "Only HasMany associations support include.separate",

"message": "Only HasMany associations support include.separate",

我有两张桌子:

| 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 模型:

If you wish to get a certain user's friends limited by 2 friends (which ones? You have to add an order option) you can query PeopleFriend including People model like this:

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 链接.

Don't forget to add associations from PeopleFriend to both People links.

这篇关于限制与 Sequelize 的belongsToMany 关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆