小编Chr*_*her的帖子

使用 Knex.js 创建嵌套返回模型

我正在使用 Knex.js 在 Hapi.js 路由中查询 MySQL 数据库。以下代码有效,但需要嵌套查询:

{
    path: '/recipes',
    method: 'GET',
    handler: (req, res) => {
        const getOperation = Knex.from('recipes')
        // .innerJoin('ingredients', 'recipes.guid', 'ingredients.recipe')
        .select()
        .orderBy('rating', 'desc')
        .limit(10)
        .then((recipes) => {
            if (!recipes || recipes.length === 0) {
                res({
                    error: true,
                    errMessage: 'no recipes found'
                });
            }

            const recipeGuids = recipes.map(recipe => recipe.guid);
            recipes.forEach(r => r.ingredients = []);
            const getOperation2 = Knex.from('ingredients')
                .whereIn('recipe', recipeGuids)
                .select()
                .then((ingredients) => {
                    recipes.forEach(r => {
                        ingredients.forEach(i => {
                            if (i.recipe === r.guid) { …
Run Code Online (Sandbox Code Playgroud)

javascript node.js knex.js hapi.js

3
推荐指数
1
解决办法
6382
查看次数

标签 统计

hapi.js ×1

javascript ×1

knex.js ×1

node.js ×1