Reputation: 1818
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",
I have 2 tables :
| peoples (id, code)
| people-friends (fk_user_id, fk_friend_id) // fk_friend_id is an id from user
My request :
await db.People.findAll({
where: {
id: parent.dataValues.id,
},
include: [
{
model: db.People,
as: "Friends",
limit: 2, // <--- LIMIT
},
],
})
People model :
People.associate = (models) => {
// People relations
models.People.belongsToMany(models.People, {
as: "Friends",
through: models.PeopleFriend,
foreignKey: "fk_user_id",
otherKey: "fk_friend_id",
})
}
Upvotes: 1
Views: 1076
Reputation: 22803
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",
},
],
})
Don't forget to add associations from PeopleFriend to both People links.
Upvotes: 1