2017-10-18 320 views
0

Postgresql數據庫。表:節點羣集

Name | equalId 

name1 | 1 
name2 | 2 
name3 | 1 
name4 | 2 
name5 | 1 

我想獲得一個由equalId排序的對象數組。例如:

[ 
{equalId: 1, names: ['name1', 'name3', 'name5']}, 
{equalId: 2, names: ['name2', 'name4']}, 
] 

我該如何處理這個問題?

我想:

await db.name.findAll({ 
     where: {equalId: {$not: null}}, 
     attributes: [ 
     'equalId', 'name' 
     ], 
     order: ['name'], 
     group: ['equalId', 'name'], 
     raw: true, 
     logging: true 
    }); 

但結果是不正確的(

回答

1

您需要進行排序和分組的結果,他們已經從數據庫中檢索後

db.name.findAll({ 
    where: {equalId: {$not: null}}, 
    attributes: ['equalId', 'name'], 
    order: ['equalId'], 
    raw: true, 
    logging: true 
}) 
.then((items) => { 
    // get an object keyed by equalId with a value of an array of names 
    const names = items.reduce((names, item) => { 
    if (!names[item.equalId]) { 
     names[item.equalId] = [item.name]; 
    } else { 
     names[item.equalId].push(item.name); 
    } 
    return names; 
    }, {}); 
    // get an array of results from the object 
    const result = Object.keys(names).map((equalId) => { 
    return { 
     equalId: equalId, 
     names: names[key], 
    }; 
    }) 
    // resolve the result array 
    return Promise.resolve(result); 
});