简体   繁体   中英

Node MYSQL How can I get a joined table in its own object?

I'm currently using this SQL query:

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 = ?
`;

Which works fine and I get this style of result:

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' }

The only problem is that I get that result for every chars in the database, I only need the subscriber once and then I need the many chars

But how can I get it so I end up with something like

RowDataPacket {
    field: blah,
    field: blah,
    charData: {
        name: 'CharName',
        locked: 'N'
    }
}

I want the joined data to be in its own object. Any information would be great thanks.

MySql always return raw array. If you want something like that, you need to format it to your needs. There are some libaries that can help you like lodash , but it's not hard task

You can solve it by go for all the rows in the array and add it to another object The other object result will have keys the email of the subscriber, and array of charsData.

For Example:

 result={
    'subscriber1@gmail:{
        'field: blah,
        field: blah,
        charsData: [{
            name: 'CharName',
            locked: 'N'
            },{
                name: 'CharName2',
                locked: 'l'
        }]
    },
    'subsriber2@yahoo':{
        Another Subscriber
    }
}

The Code:

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)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM