[英]How to filter data with sequelize
嘗試使用sequelize過濾數據,但似乎不起作用
我的模型tags
中包含以下數據tags: [{id: 1, name: 'Hey'}]
。 所以我想從這個模型中,所有的記錄tags
匹配tags
從請求什么來。 (他們有類似的數據tags: [{id: 1, name: 'Hey'}]
。但是我有所有記錄->應該只有一個
where: {
tags: {
$in: req.body.tags
}
}
對於$ in條件,標記應為值 數組 ,而不是對象數組 。
錯誤:
tags: [{id: 1, name: 'work'}, {id: 2, name: 'party'}, ... ]
正確:
// tags contains name|title of tags. now this is your choice.
tags: ['work', 'party', 'whatever', ...]
// tags contains id's of tags. for this you should change your where condition.
tags: [1, 2, 3, ...]
例:
const tagsFromRequest = [{ id: 1, name: 'work' }, { id: 2, name: 'party' }];
const tagsIds = tagsFromRequest.map(tag => tag.id);
const tagsNames = tagsFromRequest.map(tag => tag.name);
const tagsByIds = await DB.tag.findAll({
where: {
id: {
$in: tagsIds,
},
},
});
const tagsByNames = await DB.tag.findAll({
where: {
name: {
$in: tagsNames,
},
},
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.