for循环查询

来源:11-3 MySQL group分组查询

梁凤波

2019-06-13

七月老师你好,我有个问题请教一下:

我在学习此课程,另外把学习到的知识在做一个博客项目,遇到了一个查询的问题:

文章下有评论以及分类,在查询文章列表时候,同时去查询每篇文章的分类详情,和评论的总数。

第一种方法是:使用for循环,在内部异步查询,这样是可以达到我预期结果,不知道这样是否可以呢?我记得你在课程里面说不要在for循环里面查询数据库。

     // 获取文章列表
    static async getArticleList() {
        const article = await Article.scope('iv').findAll({
            where: {
                deleted_at: null
            },

        });

        for (let item of article) {
            // 查询对应文章的分类详情
            const cateogry = await CategoryDao.getCategory(item.getDataValue('category_id'));
            item.setDataValue('cateogry', cateogry);

            // 查询对应的文章评论总数
            const comments_num = await ArticleDao._getArticleComments(item.getDataValue('id'));
            item.setDataValue('comments_num', comments_num);
        }

        return article;
    }

     // 查询对应的文章评论总数
   static async _getArticleComments(article_id) {
        return await Comments.count({
            where: {
                article_id
            }
        })
    }

第二种方法:

 // 获取文章列表
    static async getArticleList() {
        const article = await Article.scope('iv').findAll({
            where: {
                deleted_at: null
            },

        });

        const articleIds = [];
        const categoryIds = [];
        article.forEach(article => {
            articleIds.push(article.id);
            categoryIds.push(article.category_id);
        });

        const category = await this._getArticleCategoryDetail(categoryIds);
        const comments = await this._getArticleComments(articleIds);
        
        // 这样查询出来不知道如何合并到 article 里面,article是一个数组

        return article;
    }

第二种方法,查询出来的分类和评论数据不知道如何合并到 article 里面,article是一个数组。

请七月老师指点一下,谢谢。

写回答

1回答

7七月

2019-06-13

第一种方法,我觉得不可取。但是如果第二种方法做不出来,用也可以,但是要限制好查询条数。不能无限制的循环查询。

第二种方法,我不太清楚为什么无法合并,即使是数组,但是数组下面的每个元素都应该有相应的分类、和评论,你需要首先设计好结构:

比如:

分类下面放文章,文章下面放评论。这肯定是可以通过3层循环遍历出来的。

0
2
梁凤波
非常感谢!
2019-06-13
共2条回复

Node.js+Koa2+MySQL打造前后端分离精品项目《旧岛》

理解异步编程本质/培养面向对象思维,独立完成Node.js服务端开发

2223 学习 · 878 问题

查看课程