sequelize-to-json icon indicating copy to clipboard operation
sequelize-to-json copied to clipboard

can't serialize nested associations

Open aphavichitr opened this issue 7 years ago • 8 comments

does this lib work with nested associations? i'm working with 2 level deep nested associations. for example models Order -> User -> UserLocation

json { order: { user: {userLocation:{ // i want data from here to be included in the json }}}

aphavichitr avatar Jan 22 '18 01:01 aphavichitr

Yes, it was made with nested associations in mind. I think you should include assoc fields explicitely (either by their names or via @assoc) as they're not added by default.

hauru avatar Jan 22 '18 11:01 hauru

Do you have to add the field names with the association in front? For example user.id or just id? If userLocation also has an id field called id, wouldn't there be a conflict?

The error i'm getting is Error: [object Object] is not a valid Sequelize model

By any chance do you have an example of a scheme that shows this?

aphavichitr avatar Jan 22 '18 21:01 aphavichitr

Well, there's an example in the readme. Nested serialization should work regardless of the depth, as long as the schemes involved are set up properly.

hauru avatar Jan 22 '18 21:01 hauru

I think my issue has to do with having nested associations that return Arrays (one to many relationship) inside the outer models. I noticed in the example it only shows how to deal with one (.serialize) or many (.serializeMany) but not both if it's contained together in the nested layers.

aphavichitr avatar Jan 22 '18 23:01 aphavichitr

Can you provide a sample of code that doesn't work?

hauru avatar Jan 26 '18 11:01 hauru

I'm trying to serialise objects created using https://github.com/overlookmotel/sequelize-hierarchy

It works if I manually specify in the serialiser how deep to nest the hierarchy but I was hoping that just being able to do something like

const hierarchicalScheme = {
  include: ['@all', 'children'],
  exclude: ['@pk', '@fk', '@auto', 'hierarchyLevel'],
  assoc: {
    children: {
      include: ['@all', 'children'],
      exclude: ['@pk', '@fk', '@auto', 'hierarchyLevel']
    }
  }
}

would be enough to recurse the serialisation all the way down. Alas if doesn't, it only does the first and second tiers.

davesag avatar May 09 '18 06:05 davesag

@davesag Seems like useful capability. I'll think about it.

hauru avatar May 10 '18 20:05 hauru

maybe something like

const hierarchicalScheme = {
  include: ['@all', 'children'],
  exclude: ['@pk', '@fk', '@auto', 'hierarchyLevel'],
  assoc: {
    children: {
      include: ['@parent']
    }
  }
}

davesag avatar May 11 '18 02:05 davesag