[英]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.