我目前正在使用此SQL查询:
var sqlQuery = `
SELECT user.ID, user.email, user.first_name, user.last_name,
user.address1, user.address2, user.country, user.gender, chars.sID, chars.name,
chars.experience, chars.locked
FROM subscriber AS user
LEFT JOIN chars on user.ID = chars.sID
WHERE user.ID = ?
`;
哪个工作正常,我得到这种风格的结果:
RowDataPacket {
[1] ID: 13,
[1] email: '[email protected]',
[1] first_name: null,
[1] last_name: null,
[1] address1: null,
[1] address2: null,
[1] country: null,
[1] gender: null,
[1] sID: 13,
[1] name: 'CharName',
[1] experience: 0,
[1] locked: 'N' }
唯一的问题是我chars
在数据库中的每一个都得到该结果,我只需要一次订阅者,然后我需要很多chars
但是我怎么得到它,所以我最终得到类似
RowDataPacket {
field: blah,
field: blah,
charData: {
name: 'CharName',
locked: 'N'
}
}
我希望加入的数据在其自己的对象中。任何信息将非常感谢。
MySql总是返回原始数组。如果您想要类似的内容,则需要将其格式化为所需的格式。有一些库可以帮助您喜欢lodash
,但是这不是一件难事
您可以通过result
遍历数组中的所有行并将其添加到另一个对象来解决该问题,另一个对象将具有订阅者电子邮件和charsData数组的键。
例如:
result={
'subscriber1@gmail:{
'field: blah,
field: blah,
charsData: [{
name: 'CharName',
locked: 'N'
},{
name: 'CharName2',
locked: 'l'
}]
},
'subsriber2@yahoo':{
Another Subscriber
}
}
代码:
var result={}
var input=YourArrayFromMySQL
for(var i=0;i<input.length;i++){
var thisLine=input[i]
//Copy the char to new variable
var thisChar= {
name:thisLine.name,
locked:thisLine.locked
}
//Delete the char from the subscribe line
delete thisLine.name
delete thisLine.locked
//If this subscriber not exsists in the result, create it, with empty array
if(!result[thisLine.email]){
result[thisLine.email]=thisLine
result[thisLine.email].charsData=[]
}
// Add to the matching subscriber the char
result[thisLine.email].charsData.push(thisChar)
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句