node.jssequelize.jsnodejs-server

Sequelize: How to Include feilds in to an include model from its include model. (I don't know if it is even possible)


I found a solution to this, but I am waiting for alternatives. I am going to hold on to my answer, and see if there are alternatives to my solution. Any one looking for solution please leave comment and I'll post my answer.

I have following Models

User
|userid|fullname   |
|1     |Joe Klan   |
|2     |Tim Thomson|
|3     |Qasim Ali  |

Task
|taskid|taskname|
|1     |TSP     |
|2     |GS1     |
|3     |GS2     |
|4     |GS3     |

Record
|recordid|userid|taskid|units|boxes|orderdate |
|1       |1     |2     |23   |43   |2023-03-04|
|2       |1     |1     |18   |25   |2023-03-04|
|3       |1     |3     |12   |15   |2023-03-04|
|4       |1     |2     |26   |58   |2023-03-04|
|5       |1     |1     |23   |76   |2023-03-04|
|6       |2     |4     |34   |19   |2023-03-04|
|7       |2     |2     |51   |88   |2023-03-04|
|8       |2     |3     |15   |73   |2023-03-04|
User.hasMany(Record,{foreignKey: 'userid'});
Record.belongsTo(Task, { foreignKey: "taskid" });

What works

    const result = await User.findAll({
      where: { userid: id },
      attributes: ["userid", "fullname"],
      include: [
        {
          model: Record,
          attributes: ["recordid", "taskid", "units", "boxes"],
          include: [{ model: Task, attributes: ["taskname"] }],
        },
      ],
    });

Sample Results:

[
  {
    userid: 1,
    fullname: "Joe Klan",
    Records: [
      {
        recordid: 1,
        taskid: 3,
        units: 23,
        boxes: 43,
        Task: {
          taskname: "GS2",
        },
      },
    ],
  },
]

What I want to do:

const result = await User.findAll({
      where: { userid: id },
      attributes: ["userid", "fullname"],
      include: [
        {
          model: Record,
          attributes: ["recordid", "taskid","Task.taskname", "units",  "boxes"],
          include: [{ model: Task, attributes: [] }],
        },
      ],
    });

Required results:

[
  {
    userid: 1,
    fullname: "Joe Klan",
    Records: [
      {
        recordid: 1,
        taskid: 3,
        taskname: "GS2",
        units: 23,
        boxes: 43,
      },
    ],
  },
]

When I try to this it says Unknown column 'Records.Task.taskname' in 'field list' which is actually correct that there is not such thing Records.Task.taskname but how can I make it to fetch Task.taskname to be included in Record attributes?


Solution

  • You have to use Sequelize.col() with separate: true. it can be used like:

    const result = await User.findAll({
      attributes: ["userid", "fullname"],
      include: [
        {
          model: Record,
          attributes: ["recordid", "taskid", [Sequelize.col("Task.taskname"), "taskname"], "units", "boxes"],
          separate: true,
          include: [{ model: Task, attributes: [] }],
        },
      ],
     where: { userid: id }
    });
    

    Hope this help.