[英]Limit on belongsToMany association with 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
},
],
})
人 model:
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 model:
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 鏈接。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.