节点MYSQL我怎样才能得到一个连接表在自己的对象?
我目前正在使用这个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: 'fakeemail@email.com', [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总是返回原始数组。 如果你想要的东西,你需要格式化为您的需求。 有一些libaries可以帮助你喜欢lodash
,但这不是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) }