![](/img/trans.png)
[英]Node/Express/mysql How to make get SQL results within jade page?
[英]jade, express, and mysql results
我正在嘗試使用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個結果集嗎? 問題在於,任何新的id_type都需要進行硬編碼...有什么想法嗎?
您可以使用lodash.groupBy
按id_type
對結果集進行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 }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.