【问题标题】:jade, express, and mysql results玉、快递和mysql结果
【发布时间】:2013-11-16 18:13:14
【问题描述】:

我正在尝试使用 Jade 呈现 SQL 查询的结果。它查询一个包含横幅的表格,每个横幅都有一个类型(总共 3 个)和一个唯一的 ID。

这就是我所拥有的:

快递:

connection.query("SELECT * FROM banner_idx ORDER BY id_type ASC, id_banner ASC", function selectCb(err, results, fields) {
        if (err) {throw err;}
        res.render('banners', {
            title: results[0].title,
            results: results
        });
    });

玉:

ul.listBanners
    - each result in results
        li.banner(data-type=result['id_type'])
        - var item = result['id_banner']+': '+result['name_banner']
        span=item

这会给我一个按我想要的顺序排列的横幅列表。现在我想以这种方式组织它(伪代码):

ul#id_type1
    list of banners with id_type == 1
ul#id_type2
    list of banners with id_type == 2
ul#id_type3
    list of banners with id_type == 3

这可能与翡翠有关吗?我应该从 Express 发送 3 个结果集而不是 1 个吗?那么问题将是任何新的 id_type 都需要硬编码......有什么想法吗?

【问题讨论】:

    标签: javascript mysql node.js express pug


    【解决方案1】:

    您可以使用lodash.groupBy 将您的结果集按id_type 分组:

    var _ = require('lodash');
    
    ...
    connection.query("SELECT * FROM banner_idx ORDER BY id_type ASC, id_banner ASC", function selectCb(err, results, fields) {
      if (err) {throw err;}
      res.render('banners', {
          title   : results[0].title,
          groups  : _.groupBy(results, 'id_type')
      });
    });
    

    groupBy 返回一个如下所示的对象:

    {
      '1' : [
        { id_type : 1, ... },
        { id_type : 1, ... },
        ...
      ],
      '2' : [
        { id_type : 2, ... },
        { id_type : 2, ... },
        ...
      ],
      ...
    }
    

    因此,该对象中的键是您要分组的属性的值,在本例中为 id_type

    您的模板看起来像这样:

    each entries, id in groups
      ul(id = 'id_type' + id)
        each entry in entries
          li #{ entry.id_banner + ': ' + entry.name_banner }
    

    【讨论】:

      猜你喜欢
      • 2015-11-25
      • 2015-08-18
      • 2011-05-19
      • 1970-01-01
      • 2015-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-25
      相关资源
      最近更新 更多