Error when add new record with relationship db

Hello @chumanhhung235,

I tried to reproduce your issue, but had no success.
Based from this database definition:

create table if not exists department
(
	id serial not null constraint department_pk primary key,
	name varchar
);

create table if not exists employee
(
	id serial not null constraint employee_pk primary key,
	name varchar
);

create table if not exists department_employee
(
	id serial not null constraint department_employee_pk primary key,
	department_id integer not null constraint department_employee_department_id_fk references department,
	employee_id integer not null constraint department_employee_employee_id_fk references employee,
	name varchar
);

Lumber will generate these models:

const Department = sequelize.define('department', {
    name: {
      type: DataTypes.STRING,
    },
  }, {
    tableName: 'department',
    timestamps: false,
    schema: process.env.DATABASE_SCHEMA,
  });

const Employee = sequelize.define('employee', {
    name: {
      type: DataTypes.STRING,
    },
  }, {
    tableName: 'employee',
    timestamps: false,
    schema: process.env.DATABASE_SCHEMA,
  });

const DepartmentEmployee = sequelize.define('departmentEmployee', {
    name: {
      type: DataTypes.STRING,
    },
  }, {
    tableName: 'department_employee',
    timestamps: false,
    schema: process.env.DATABASE_SCHEMA,
  });

Associations are:

Department.associate = (models) => {
    Department.hasMany(models.departmentEmployee, {
      foreignKey: {
        name: 'departmentIdKey',
        field: 'department_id',
      },
      as: 'departmentEmployees',
    });
  };

Employee.associate = (models) => {
    Employee.hasMany(models.departmentEmployee, {
      foreignKey: {
        name: 'employeeIdKey',
        field: 'employee_id',
      },
      as: 'departmentEmployees',
    });
  };

DepartmentEmployee.associate = (models) => {
    DepartmentEmployee.belongsTo(models.department, {
      foreignKey: {
        name: 'departmentIdKey',
        field: 'department_id',
      },
      as: 'department',
    });
    DepartmentEmployee.belongsTo(models.employee, {
      foreignKey: {
        name: 'employeeIdKey',
        field: 'employee_id',
      },
      as: 'employee',
    });
  };

And I have no issue adding new “DepartmentEmployee” records or list them.

Do you have an equivalent of these definitions?

Let me know :slight_smile: