2

I have multiple includes in single query of sequelize but I can't get the result as I want. please refer below code

const users = await User.findAll({
  include: {
    model: Tool,
    as: 'Instruments',
    include: {
      model: Teacher,
      include: [ /* etc */ ]
    }
  }
});

output:

[{
  "name": "John Doe",
  "id": 1,
  "Instruments": [{ // 1:M and N:M association
    "name": "Scissor",
    "id": 1,
    "userId": 1,
    "Teacher": { // 1:1 association
      "name": "Jimi Hendrix"
    }
  }]
}]

now I want output like

    [{
      "name": "John Doe",
      "id": 1,
      "Instruments": { // 1:M and N:M association
        "name": "Scissor",
        "id": 1,
        "userId": 1
      },
      "Teacher": { // 1:1 association
        "name": "Jimi Hendrix"
      }
    }]

It's possible if yes then how ??

chirag sorathiya
  • 1,223
  • 8
  • 29

1 Answers1

0

As the relation stated

USER (m)------(n) INSTRUMENTS (1)------(1) TEACHER

So

  1. Every single instruments has a teacher and every teacher teaches an instrument.
  2. Every single user can learn multiple instrument and every instrument can learn by multiple users.

Based on these relation between USER and TEACHER is following

USER (m)------(n) TEACHER

  1. Every single user can learn instrument from multiple teacher.
  2. Every single teacher can teach instrument multiple user.

Your original output was

[{
  "name": "John Doe",
  "id": 1,
  "Instruments": [{ // 1:M and N:M association
    "name": "Scissor",
    "id": 1,
    "userId": 1,
    "Teacher": { // 1:1 association
      "name": "Jimi Hendrix"
    }
  }]
}]

What do you expect if there is multiple instrument ? like following

[{
  "name": "John Doe",
  "id": 1,
  "Instruments": [{ // 1:M and N:M association
    "name": "Scissor",
    "id": 1,
    "userId": 1,
    "Teacher": { // 1:1 association
      "name": "Jimi Hendrix"
    }
  },
  {
    "name": "Guitar",
    "id": 2,
    "userId": 1,
    "Teacher": {
      "name": "john wick"
    }
  }]
}]

If you make flat of instrument then you always can post processing of your result after receiving from sequelize.

const result = [{
  "name": "John Doe",
  "id": 1,
  "Instruments": [{ // 1:M and N:M association
    "name": "Scissor",
    "id": 1,
    "userId": 1,
    "Teacher": { // 1:1 association
      "name": "Jimi Hendrix"
    }
  },
  {
    "name": "Guitar",
    "id": 2,
    "userId": 1,
    "Teacher": {
      "name": "john wick"
    }
  }]
}]

console.log(result.map(function(obj) {
  return obj.Instruments.map(function(iObj) {
      const teacher = iObj.Teacher;
      delete iObj.Teacher;
      return {
        name: obj.name,
        id: obj.id,
        Instrument: iObj,
        Teacher: teacher
      }
    });
}).flat())
Ratul Sharker
  • 7,484
  • 4
  • 35
  • 44