Hi,
I am trying to create associations between my models , but i keep getting this error:
SequelizeEagerLoadingError
A worker can have many jobs , and a job belongs to one worker.
A client can have any jobs , and a job has one client
I have tried using this method
Model.hasMany(ChildModel, {foreignKey : 'id'})
but it also doesnt work.When i use associations i also get an error. If anybody could help me understand what im doing wrong or recommend something i can read i will highly appreciate.
The worker model , the dbconfig contains my connection to the db
const sequelize = require("../dbconfig");
const DataTypes = require('sequelize');
const Joi = require("joi");
const Worker = sequelize.sequelize.define(
'workers',
{
id: {
autoIncrement: true,
type: DataTypes.BIGINT,
allowNull: false,
primaryKey: true
},
username: {
type: DataTypes.STRING(255),
allowNull: false
}
}, {
sequelize,
tableName: 'workers',
schema: 'public',
timestamps: false,
underscored: true,
indexes: [
{
name: "worker_profiles_pkey",
unique: true,
fields: [
{ name: "id" },
]
},
]
}
);
function validateWorker(Worker) {
const schema = Joi.object({
username: Joi.string()
.min(3)
.max(191)
.required()
});
return schema.validate(Worker);
}
Worker.associate = function(models) {
Worker.hasMany(models.Job, {
foreignKey : "worker_id",
as: 'jobs'
});
}
Worker.associate = function(models) {
Worker.belongsTo(models.User, {
foreignKey : "user_id",
sourceKey : 'id'
});
}
exports.Worker = Worker;
exports.validateWorker = validateWorker;
My job model looks like this :
const sequelize = require("../dbconfig");
const DataTypes = require("sequelize");
const Joi = require("joi");
const Job = sequelize.sequelize.define(
'jobs',
{
id: {
autoIncrement: true,
type: DataTypes.BIGINT,
allowNull: false,
primaryKey: true
},
worker_id: {
type: DataTypes.BIGINT,
allowNull: true,
references: {
model: 'workers',
key: 'id'
}
},
}, {
sequelize,
tableName: 'jobs',
schema: 'public',
timestamps: false,
underscored: true,
indexes: [
{
name: "jobs_pkey",
unique: true,
fields: [
{ name: "id" },
]
},
]
}
);
function validateJob(job) {
const schema = Joi.object({
title: Joi.string()
.min(3)
.max(191)
.required(),
worker_id: Joi.number(),
}).unknown(true);
return schema.validate(job);
};
Job.associate = function(models) {
Job.belongsTo(models.Worker, {
foreignKey : "worker_id",
as : 'worker'
});
}
module.exports.Job = Job;
exports.validateJob = validateJob;