postgresql 序列化模型联接

zaqlnxep  于 2023-11-18  发布在  PostgreSQL
关注(0)|答案(1)|浏览(148)

我正在使用Node和Express、Sequelize和PostgreSQL构建一个API。
我有属于一个部门的雇员,我有两个表雇员和部门。
我在我的项目中有以下两个模型,我使用sequelize-cli创建了模型和迁移。关联和外键生成似乎按预期工作,当我浏览PostgreSQL时,我看到了fk约束。
employee model

'use strict';
const {
  Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
  class Employees extends Model {
    /**
     * Helper method for defining associations.
     * This method is not a part of Sequelize lifecycle.
     * The `models/index` file will call this method automatically.
     */
    static associate(models) {
      // define association here
    }
  }
  Employees.init({
    first_name: {
      type: DataTypes.STRING,
      allowNull: false
    },
    last_name: {
      type: DataTypes.STRING,
      allowNull: false
    },
    departmentId: {
      type: DataTypes.STRING,
      allowNull: false
    },
    createdBy: {
      type: DataTypes.STRING,
      allowNull: false
    },
    updatedBy: {
      type: DataTypes.STRING
    }
  }, {
    sequelize,
    modelName: 'Employees',
  });
 
  // UPDATED per suggestions
  Employees.associate = function(models) {
    Employees.belongsTo(models.Departments, {
      foreignKey: 'departmentId',
      as: "dept",
      onDelete: 'SET NULL',
    });
  };

  return Employees;
};

字符串
departments model

'use strict';
const {
  Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
  class Departments extends Model {
    /**
     * Helper method for defining associations.
     * This method is not a part of Sequelize lifecycle.
     * The `models/index` file will call this method automatically.
     */
    static associate(models) {
      // define association here
    }
  }
  Departments.init({
    name: {
      type: DataTypes.STRING,
      allowNull: false
    },
    description: {
      type: DataTypes.STRING
    },
    createdBy: {
      type: DataTypes.STRING,
      allowNull: false
    },
    updatedBy: {
      type: DataTypes.STRING
    }
  }, {
    sequelize,
    modelName: 'Departments',
  });

  // UPDATED per suggestions
  Departments.associate = function(models) {
    Departments.hasMany(models.Employees, {
      foreignKey: 'departmentId',
      as: "employees"
    });
  };

  return Departments;
};


employees migration

departmentId: {
        type: Sequelize.INTEGER,
        onDelete: 'SET NULL',
        references: {
          model: {
            tableName: 'Departments',
          },
          key: 'id',
        },
      },


这一切似乎都很好,如果我试图创建一个没有有效部门ID的员工,我会得到一个预期的约束错误。
当我找到所有使用const employees = await this.db.employees.findAndCountAll();的员工时,我会收到如下所示的响应

{
    "count": 1,
    "rows":
    [
        {
            "id": 1,
            "first_name": "jon",
            "last_name": "doe",
            "departmentId": 1,
            "createdBy": "jane.dough"
        }
    ]
}


这一切都像预期的那样工作。
TLDR;
但是,当我尝试包含Departments模型(将Department Name与Department ID连接起来)时,const employees = await this.db.employees.findAndCountAll({include: [{model: this.db.departments,as: 'dept'}]});

I get the following association error.
"SequelizeEagerLoadingError: Departments is not associated to Employees!"


我如何修复关联以将这些连接在一起。
更新:在应用@nazrul-chowdhury建议的更改后,我仍然看到错误。
我发布了我如何初始化数据库和模型的相关代码.
employeeRepository.js

const { connect } = require('../config/db.config');

class EmployeeRepository {

    db = {};

    constructor() {
        this.db = connect();

    }

    async getEmployees() {
        try {
            const employees = await this.db.employees.findAndCountAll({include: [{model: this.db.departments,as: 'dept'}]});


db.config

const { Sequelize, Model, DataTypes } = require("sequelize");
// const logger = require('../logger/api.logger');

const connect = () => {

    const hostName = process.env.HOST;
    const userName = process.env.USER;
    const password = process.env.PASSWORD;
    const database = process.env.DB;
    const dialect = process.env.DIALECT;
    
    const sequelize = new Sequelize(database, userName, password, {
        host: hostName,
        dialect: dialect,
        operatorsAliases: 0,
        pool: {
            max: 10,
            min: 0,
            acquire: 20000,
            idle: 5000
        },
        logging: false
    });
    // turn off logging in production (log to console in all other environments)
    // logging: process.env.NODE_ENV === 'production' ? false : console.log

    const db = {};
    db.Sequelize = Sequelize;
    db.sequelize = sequelize;
    db.departments = require("../models/departments.model")(sequelize, DataTypes, Model);
    db.employees = require("../models/employees.model")(sequelize, DataTypes, Model);

    return db;

}

module.exports = {
    connect
}

brjng4g3

brjng4g31#

您已经定义了员工和部门之间的一对一关联,但实际上您需要一对多关系,其中每个员工属于一个部门,并且每个部门可以有多个员工。要修复该关联,您应该对模型进行一些更改。
在员工模型中,将关联定义更改为使用HASSONE而不是HASONE来指示员工属于某个部门。此外,您需要更新外键以匹配模型中的字段名称。

Employees.associate = function(models) {
  Employees.belongsTo(models.Departments, {
    foreignKey: 'departmentId', // Use the correct foreign key field
    as: 'dept',
    onDelete: 'SET NULL',
  });
};

字符串
在departments模型中,您应该删除datasTo关联,因为部门并不直接属于员工。相反,如果您想检索与部门关联的员工,则可以在Departments模型中使用hasMany关联,

Departments.associate = function(models) {
  Departments.hasMany(models.Employees, {
    foreignKey: 'departmentId', // Use the correct foreign key field
    as: 'employees',
  });
};

相关问题