gpt4 book ai didi

javascript - 如何使用sequelize过滤数据

转载 作者:行者123 更新时间:2023-11-28 04:07:40 24 4
gpt4 key购买 nike

尝试使用sequelize过滤数据,但似乎不起作用

我的模型标签中有以下数据标签:[{id: 1, name: 'Hey'}]。所以我试图从这个模型中获取所有记录,其中 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,
},
},
});

关于javascript - 如何使用sequelize过滤数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46553128/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com