NodeJS 如何在sequelize中应用联合查询

7tofc5zh  于 12个月前  发布在  Node.js
关注(0)|答案(1)|浏览(152)

Project.model.ts

import { DataTypes, Model, CreationOptional, InferCreationAttributes, InferAttributes, BelongsToManyGetAssociationsMixin, BelongsToManySetAssociationsMixin, BelongsToManyAddAssociationsMixin } from 'sequelize';
import sequelize from '../../loaders/db'; // config of sequelize
import Manager from '../manager/manager.model';

const tableName = 'project';

export interface ProjectModel extends Model<InferAttributes<ProjectModel>, InferCreationAttributes<ProjectModel>>  {
  id:  CreationOptional<number>;
  name: string;
  managerId: number | null;
}

const Project = sequelize().define<ProjectModel>(
  tableName,
  {
    id: {
      type: DataTypes.UUID,
      primaryKey: true,
      defaultValue: DataTypes.UUIDV4,
    },
    name: {
      type: DataTypes.STRING(100),
      allowNull: false,
    },
    managerId: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: {
        model: Manager, // Reference Manager model
        key: 'id',
      },
      field: 'conformance_id',
    },
  },
  {
    timestamps: false,
  }
);

export default Project;

字符串
Page.model.ts

import { DataTypes, Model, CreationOptional, InferCreationAttributes, InferAttributes, BelongsToManyGetAssociationsMixin, BelongsToManySetAssociationsMixin, BelongsToManyAddAssociationsMixin } from 'sequelize';
import sequelize from '../../loaders/db'; // config of sequelize
import Project from '../project/project.model';

const tableName = 'page';

export interface PageModel extends Model<InferAttributes<PageModel>, InferCreationAttributes<PageModel>> {
  id: CreationOptional<number>;
  projectId: number; // Foreign key to link with the Project model
  name: string;
}

const Page = sequelize().define<PageModel>(
  tableName,
  {
    id: {
      type: DataTypes.UUID,
      primaryKey: true,
      defaultValue: DataTypes.UUIDV4,
    },
    projectId: {
      type: DataTypes.UUID,
      allowNull: false,
      references: {
        model: Project, // Reference Project model
        key: 'id',
      },
      field: 'project_id'
    },
    name: {
      type: DataTypes.STRING(50),
      allowNull: true,
      field: 'name'
    },
  },
  {
    timestamps: false,
  }
);

export default Page;


Manager.model.ts

import { DataTypes, Model, CreationOptional, InferCreationAttributes, InferAttributes, BelongsToManyGetAssociationsMixin, BelongsToManySetAssociationsMixin, BelongsToManyAddAssociationsMixin } from 'sequelize';
import sequelize from '../../loaders/db'; // config of sequelize

const tableName = 'manager';

export interface ManagerModel extends Model<InferAttributes<ManagerModel>, InferCreationAttributes<ManagerModel>> {
  id: CreationOptional<number>;
  level: string; // Foreign key to link with the Project model
  name: string;
}

const Manager = sequelize().define<ManagerModel>(
  tableName,
  {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true,
    },
    level: {
      type: DataTypes.STRING(10),
      allowNull: false,
    },
    name: {
      type: DataTypes.STRING(50),
      allowNull: true,
      field: 'name'
    },
  },
  {
    timestamps: false,
  }
);

export default Manager;


Project.service.ts

import { Service } from 'typedi';
import Project from './project.model';

@Service()
export default class ProjectService {
  async getProjectById(id: string) {
    try {
      const project = await Project.findOne({
        where: { id },
        // remaining part of the query to get manager and page details using any operator
      });
      if (!project) {
        throw new Error('Project not found');
      }
      return project;
    } catch (error) {
      throw new Error('Failed to fetch Project by ID');
    }
  }
}


我是新来的这个Sequelize。现在我不知道什么样的查询,我必须添加项目。findOne()方法。我需要从经理表和页面数组与该项目相关联的经理名称。提前感谢您的帮助和时间。

5f0d552i

5f0d552i1#

下面是一个(未经测试的)示例,使用include指定关联的模型(Manager和Page)沿着要包含在结果中的属性。因此,这应该会获取一个项目以及Manager的名称和关联页面的数组。

import { Op } from 'sequelize';
import Project from './project.model';
import Manager from '../manager/manager.model';
import Page from '../page/page.model';

@Service()
export default class ProjectService {
  async getProjectById(id: string) {
    try {
      const project = await Project.findOne({
        where: { id },
        include: [
          {
            model: Manager,
            attributes: ['name'], // Include only the 'name' attribute of the Manager model
          },
          {
            model: Page,
            attributes: ['name'], // Include only the 'name' attribute of the Page model
          },
        ],
      });
      if (!project) {
        throw new Error('Project not found');
      }
      return project;
    } catch (error) {
      throw new Error('Failed to fetch Project by ID');
    }
  }
}

字符串

相关问题