我正在尝试为我的查询确定更好的方法。我有两张桌子,一张是食谱,另一张是评论。目前,我有两个单独的查询来查找配方,然后找到与配方相关的评论。我有更好的方法吗?
RecipeController
module.exports = {
viewRecipe: function(req, res) {
var recipeId = parseInt(req.params.id, 10);
var recipeM = {};
var reviewM = {};
db.recipe.find({
where: {
id: recipeId
}
}).then(function(recipe) {
recipeM = recipe.dataValues;
recipeM.ingredients = recipe.ingredients.replace(/\s+/g, '').split(",");
recipeM.instructions = recipe.instructions.split("\n");
}, function (e) {
});
db.review.findAll({
where: {
recipeId: recipeId
}
}).then(function(review) {
console.log(review);
res.render('viewRecipe', { recipe: recipeM, review: review, categories: categoriesMain, title: recipeM.title });
}, function(e) {
});
},
答案 0 :(得分:1)
如果您被允许使用ES6生成器,您可以从npm模块co
应用co.wrapmodule.exports = {
viewRecipe: co.wrap(function*(req, res) {
var recipeId = parseInt(req.params.id, 10);
var recipeM = {};
var reviewM = {};
var recipe = yield db.recipe.find({
where: {
id: recipeId
}
});
recipeM = recipe.dataValues;
recipeM.ingredients = recipe.ingredients.replace(/\s+/g, '').split(",");
recipeM.instructions = recipe.instructions.split("\n");
var review = yield db.review.findAll({
where: {
recipeId: recipeId
}
});
console.log(review);
res.render('viewRecipe', { recipe: recipeM, review: review, categories: categoriesMain, title: recipeM.title });
}).catch(function(e){
}),
答案 1 :(得分:0)
如果您在食谱和评论之间建立了关系,我相信您可以使用Sequelize的包含选项,如下所示:
db.recipe
.findById(req.params.id, {
include: [{
model: review
}]
})
.then(function(recipe) {
// your success code
})
.catch(function(err) {
// you error code
});
据我所知,include选项可用作左连接。此外,这应该会更好,因为只会在数据库上运行一个查询。