我的代码在下面。第一种方法是有效的,后来我想给category_id作为url参数不能找到一个解决方案。你可以看出来,我是第一次拍续集。如果有人能帮助我,我还是很感激的。
itemRouter.get('/', async (req, res) => {
const items = await Item.findAll()
res.json(items) // THIS WORKS FINE
})
itemRouter.get('/ct/:ctid', async (req, res) => {
const itemsByCategory = await SOMETHING
res.json(itemsByCategory)
})
是否创建关联?假设Item模型与Category
有关联itemRouter.get('/ct/:ctid', async (req, res) => {
const itemsByCategory = await Item.findAll({
include: {
model: Category,
required: true, //for inner join
where : {
id: req.params.ctid
}
}
});
return res.json(itemsByCategory)
})
查询:查找与类别模型有关联的所有项目,同时该项目所属的类别必须具有id = ctid。
文档:https://sequelize.org/master/manual/eager-loading.html eager-loading-filtered-at-the-associated-model-level