如何在sequelize中应用联合查询

问题描述 投票:0回答:1

项目.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;

页面.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;

项目.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');
    }
  }
}

我是这个续集的新手。现在我不确定必须添加 Project.findOne() 方法什么样的查询。我需要来自与该项目关联的管理器表和页面数组的管理器名称。预先感谢您的帮助和时间。

node.js typescript postgresql express sequelize.js
1个回答
0
投票

这是一个(未经测试的)示例,使用

include
指定关联的模型(Manager 和 Page)以及要包含在结果中的属性。因此,这应该获取一个项目以及经理的姓名和相关页面的数组。

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');
    }
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.