select columns from right side table in inner join using sequelize

陌路散爱 提交于 2021-02-08 12:07:12

问题


I'm implementing API using Sequelize in node.js. I have three tables i.e. users, projects and userprojects. Here, userprojects table contains foreign key columns i.e. UserId and ProjectId from users and projects table respectively (as shown in picture below)

I want to inner join userprojects and projects table so I get final flat result as Project Id (from userproject table) and Project Name (from project table) in a flat format e.g.

7AD60938-60F5-433D-A55B-2F48A9931EFA | Project 01

2582A40C-7FB9-4AA8-B78E-0A13D0FC75EA | Project 02

I have written following code in my controller in node.js

const sequelize = require("Sequelize");
const db = require("../config/db.config");

exports.GetData = (req, res) => {
  if (!req.query.userId)
    return res.status(400).send("Invalid arguments specified");

  db.userprojects
    .findAll({
      where: { userId: req.query.userId },
      include: [
        {
          model: db.projects,
          attributes: [],
          required: true,
        },
      ],
      attributes: ["ProjectId", sequelize.col("db.projects.Name")],
    })
    .then((projects) => {
      return res.status(200).json(projects);
    })
    .catch((err) => {
      console.log(err);
    });
};

When I call this method, it gives runtime error :

TypeError: attr.includes is not a function at \src\API\node_modules\sequelize\lib\dialects\abstract\query-generator.js:1445:22 at Array.map () at MSSQLQueryGenerator.escapeAttributes (\src\API\node_modules\sequelize\lib\dialects\abstract\query-generator.js:1417:37) at MSSQLQueryGenerator.selectQuery (\src\API\node_modules\sequelize\lib\dialects\abstract\query-generator.js:1172:28) at MSSqlQueryInterface.select (\src\API\node_modules\sequelize\lib\dialects\abstract\query-interface.js:953:27) at Function.findAll (\src\API\node_modules\sequelize\lib\model.js:1753:47)

I assume problem is with line attributes: ["ProjectId", sequelize.col("db.projects.Name")] if I remove "sequelize.col("db.projects.Name")" then call works fine.

What could be the issue here? In nutshell, I want to implement inner join with flat hierarchy result as shown above. Any help/document to fix this issue?

来源:https://stackoverflow.com/questions/66064626/select-columns-from-right-side-table-in-inner-join-using-sequelize

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!