我正在尝试使用 Jade 呈现 SQL 查询的结果。它查询一个包含横幅的表,每个横幅都有一个类型(总共 3 个)和一个唯一的 ID。
这是我的:
express :
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
});
});
Jade :
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
这可能与 Jade 有关吗?我应该从 Express 发送 3 个结果集而不是 1 个吗?那么问题就是任何新的 id_type 都需要硬编码......有什么想法吗?
最佳答案
您可以使用 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 }
关于javascript - jade、express 和 mysql 结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19796311/