Sequelize include multiple tables in query - mysql

So i have the following structure receipts -> policies -> policholders
Every receipt belongs to a policy and every policy belong to a policyholder
What i want to do is when i fetch receipts i get an object back with the both the policy and policyholder included (i am using feathers-sequelize, hook is included below). I get the error that policyholders is not associated to receipts
Desired response:
{
"ReceiptId": 1,
"Supplement": 10.1,
"policy": {
"PolicyNumber": 1234
},
"policyholder": {
"Name": "Joe",
"Surname": "Blogs"
}
}
Policies model
// See http://docs.sequelizejs.com/en/latest/docs/models-definition/
// for more of what you can do here.
const Sequelize = require("sequelize");
const DataTypes = Sequelize.DataTypes;
module.exports = function (app) {
const sequelizeClient = app.get("sequelizeClient");
const policies = sequelizeClient.define(
"policies",
{
PolicyId: {
autoIncrement: true,
type: DataTypes.INTEGER,
allowNull: false,
primaryKey: true,
},
PolicyNumber: {
type: DataTypes.STRING(30),
allowNull: true,
},
CompanyId: {
type: DataTypes.INTEGER,
allowNull: true,
},
PolicyholderId: {
type: DataTypes.INTEGER,
allowNull: true,
},
},
{
hooks: {
beforeCount(options) {
options.raw = true;
},
},
}
);
// eslint-disable-next-line no-unused-vars
policies.associate = function (models) {
// Define associations here
// See http://docs.sequelizejs.com/en/latest/docs/associations/
const { policyholders, companies } = models;
policies.belongsTo(policyholders, { foreignKey: "PolicyholderId" });
};
return policies;
};
Policyholder model
// See http://docs.sequelizejs.com/en/latest/docs/models-definition/
// for more of what you can do here.
const Sequelize = require("sequelize");
const DataTypes = Sequelize.DataTypes;
module.exports = function (app) {
const sequelizeClient = app.get("sequelizeClient");
const policyholders = sequelizeClient.define(
"policyholders",
{
PolicyholderId: {
autoIncrement: true,
type: DataTypes.INTEGER,
allowNull: false,
primaryKey: true,
},
Name: {
type: DataTypes.STRING(250),
allowNull: true,
},
Surname: {
type: DataTypes.STRING(250),
allowNull: true,
},
},
{
hooks: {
beforeCount(options) {
options.raw = true;
},
},
}
);
// eslint-disable-next-line no-unused-vars
policyholders.associate = function (models) {
// Define associations here
// See http://docs.sequelizejs.com/en/latest/docs/associations/
const { policies } = models;
policyholders.hasMany(policies, { foreignKey: "PolicyholderId" });
};
return policyholders;
};
receipts model
// See http://docs.sequelizejs.com/en/latest/docs/models-definition/
// for more of what you can do here.
const Sequelize = require("sequelize");
const DataTypes = Sequelize.DataTypes;
module.exports = function (app) {
const sequelizeClient = app.get("sequelizeClient");
const receipts = sequelizeClient.define(
"receipts",
{
ReceiptId: {
autoIncrement: true,
type: DataTypes.INTEGER,
allowNull: false,
primaryKey: true,
},
PolicyId: {
type: DataTypes.INTEGER,
allowNull: true,
},
Supplement: {
type: DataTypes.INTEGER,
allowNull: true,
},
},
{
hooks: {
beforeCount(options) {
options.raw = true;
},
},
}
);
// eslint-disable-next-line no-unused-vars
receipts.associate = function (models) {
// Define associations here
// See http://docs.sequelizejs.com/en/latest/docs/associations/
const { policies } = models;
receipts.belongsTo(policies, { foreignKey: "PolicyId" });
};
return receipts;
};
get related hook
module.exports = function (options = {}) {
return async (context) => {
const { include, ...query } = context.params.query;
const Policies = context.app.services.policies.Model;
const Policyholders = context.app.services.policyholders.Model;
context.params.sequelize = {
include: [Policies, Policyholders],
raw: false,
};
// Update the query to not include `include`
context.params.query = query;
return context;
};
};

If Placeholders is linked to Receipts through Policies then you need to indicate Placeholders in an include option of Policies itself:
context.params.sequelize = {
include: [{
model: Policies,
include: [Policyholders]
}],
raw: false,
};

Related

TypeError: models.leaves.getAllEmpoyees is not a function

I am writing a function in Schema Model for getting Data with a query. The query is working fine, but unfortunately i am getting an error regarding Function - getAllEmpoyees() not found. For Reference - my sequelize version is - 6.15.0 . I am new to Node.js. Can anyone help me out yrr, Thanks in Advance!
const Sequelize = require('sequelize');
module.exports = function(sequelize, DataTypes) {
return sequelize.define('leaves', {
id: {
autoIncrement: true,
type: DataTypes.BIGINT.UNSIGNED,
allowNull: false,
primaryKey: true
},
employee_id: {
type: DataTypes.INTEGER,
allowNull: false
},
leave_type_id: {
type: DataTypes.INTEGER,
allowNull: false
},
leave_reason: {
type: DataTypes.STRING(255),
allowNull: false
},
remark: {
type: DataTypes.STRING(255),
},
status: {
type: DataTypes.STRING(255),
allowNull: false
},
created_by: {
type: DataTypes.INTEGER
}
},
{
sequelize,
tableName: 'leaves',
timestamps: true,
indexes: [
{
name: "PRIMARY",
unique: true,
using: "BTREE",
fields: [
{ name: "id" },
]
},
]
},
getAllEmpoyees = function() {
var query = "select * from leaves as l join leave_types as lt on l.leave_type_id=lt.id";
return sequelize.query(query, { type: sequelize.QueryTypes.SELECT});
},
);
};
const express = require('express');
const router = express.Router();
var path = require('path');
var root_path = path.dirname(require.main.filename);
var models = require(root_path + '/models');
var moment = require("moment");
router.get('/getallemployeeLeaves', (req, res) => {
console.log("All Fetched");
models.leaves.getAllEmpoyees().then(function (data) {
console.log("");
if (data.length > 0) {
res.json({
status: 200,
data: data
})
} else {
res.json({
status: 400,
})
}
})
})

Adding Many to Many Data Sequelize

Case: I have 2 tables; one for users and one for assignments. A user can have many assignments and an assignment can be assigned to many users. I have a form in the frontend to add assignment and assign the users for the assignment and I am really confused on how to add the assignment and user to the joint table 'user_assignment'. Can someone point where I am having the mistake? Also for this, I refer to Advanced M:N Associations.
I also attach my code for the Users and Assignments model, and other relevant code parts.
user.model.js
module.exports = (sequelize, DataTypes) => {
const User = sequelize.define("users", {
firstName: {
type: DataTypes.STRING,
allowNull: false,
},
lastName: {
type: DataTypes.STRING,
allowNull: false,
},
department: {
type: DataTypes.STRING,
allowNull: false,
},
email: {
type: DataTypes.STRING,
allowNull: false,
},
password: {
type: DataTypes.STRING,
allowNull: false,
},
role: {
type: DataTypes.STRING,
allowNull: false,
},
});
return User;
};
assignment.model.js
module.exports = (sequelize, DataTypes) => {
const Assignment = sequelize.define("assignments", {
title: {
type: DataTypes.STRING,
allowNull: false,
},
department: {
type: DataTypes.STRING,
allowNull: false,
},
urgency: {
type: DataTypes.STRING,
allowNull: false,
},
assignmentBegin: {
type: DataTypes.STRING,
allowNull: false,
},
assignmentEnd: {
type: DataTypes.STRING,
allowNull: false,
},
description: {
type: DataTypes.STRING,
allowNull: false,
},
});
return Assignment;
};
database/index.js
...
db.user = require("../models/user.model")(sequelize, Sequelize);
db.assignment = require("../models/assignment.model")(sequelize, Sequelize);
...
db.user.belongsToMany(db.assignment, {
through: "user_assignment",
as: "assignments",
foreignKey: "userId",
});
db.assignment.belongsToMany(db.user, {
through: "user_assignment",
as: "users",
foreginKey: "assignmentId",
});
...
assignment.controller.js
const db = require("../database");
const Assignment = db.assignment;
const User = db.user;
exports.create = async (req, res) => {
const {
participant,
title,
department,
urgency,
assignmentBegin,
assignmentEnd,
description,
} = req.body;
await Assignment.create({
title: title,
department: department,
urgency: urgency,
assignmentBegin: assignmentBegin,
assignmentEnd: assignmentEnd,
description: description
}).then(async result => {
for (i = 0; i < participant.length; i++) {
const user = await User.findByPk(participant[i])
// console.log(user.id)
await UserController.addAssignment(user.id, result.id);
// await UserController.addAssignment(2, 1)
}
}).catch(err => {
res.json({ message: "ERROR WHILE CREATING ASSIGNMENT!" });
console.log(">>> ERROR WHILE CREATING ASSIGNMENT!")
});
}
Any pointers on what I should do would be great!
I'd recommend you define the model associations inside each of the model files. Also you should hash/encrypt your passwords before saving them to the DB, you can use the .comparePassword() function outside of the model in a controller when logging in etc.
models/User.js
const Promise = require('bluebird')
const bcrypt = Promise.promisifyAll(require('bcrypt'))
function hashPassword (user) {
const SALT_FACTOR = 12
if (!user.changed('password')) {
return;
} else {
user.setDataValue('password', bcrypt.hashSync(user.password, SALT_FACTOR))
}
}
module.exports = User = (sequelize, DataTypes) => {
const User = sequelize.define('User', {
firstName: {
type: DataTypes.STRING,
allowNull: false,
},
lastName: {
type: DataTypes.STRING,
allowNull: false,
},
department: {
type: DataTypes.STRING,
allowNull: false,
},
email: {
type: DataTypes.STRING,
allowNull: false,
},
password: {
type: DataTypes.STRING,
allowNull: false,
},
role: {
type: DataTypes.STRING,
allowNull: false,
},
{
hooks: {
beforeCreate: hashPassword,
beforeUpdate: hashPassword
}
})
User.associate = models => {
User."Association type here"(models."Model to associate",
{Options (For many to many add your "through" table here)}
)
// Example:
User.belongsToMany(models.Assignment, {
through: "UserAssignment"
})
}
User.prototype.comparePassword = function (password) {
return bcrypt.compareSync(password, this.password)
}
return User
}
And in the associated Model (models/Assignment.js):
module.exports = Assignment = (sequelize, DataTypes) => {
const Assignment = sequelize.define('Assignment', {
title: {
type: DataTypes.STRING,
allowNull: false,
},
department: {
type: DataTypes.STRING,
allowNull: false,
},
urgency: {
type: DataTypes.STRING,
allowNull: false,
},
assignmentBegin: {
type: DataTypes.STRING,
allowNull: false,
},
assignmentEnd: {
type: DataTypes.STRING,
allowNull: false,
},
description: {
type: DataTypes.STRING,
allowNull: false,
},
},
{
timestamps: false
})
Assignment.associate = models => {
Assignment.belongsToMany(models.User, {
through: "UserAssignment"
})
}
return Role
}
The joint table (models/UserAssignment.js):
module.exports = UserAssignment = (sequelize, DataTypes) => {
const UserAssignment = sequelize.define('UserAssignment', {
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true
}
},
{
timestamps: false
})
return UserAssignment
}
And finally my index.js file (models/index.js), it programatically adds the models to the DB:
'use strict';
const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const basename = path.basename(__filename);
const env = process.env.NODE_ENV || 'development';
const config = require(__dirname + '/../config/config.json')[env];
const db = {};
let sequelize;
if (config.use_env_variable) {
sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
sequelize = new Sequelize(config.database, config.username, config.password, config);
}
fs
.readdirSync(__dirname)
.filter(file => {
return (file.indexOf('.') !== 0)
&& (file !== basename)
&& (file.slice(-3) === '.js');
})
.forEach(file => {
const model = require(path.join(__dirname, file))(sequelize, Sequelize.DataTypes);
db[model.name] = model;
});
Object.keys(db).forEach(modelName => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = db;
As an extra note, you can shorten down your createAssignment function in your controller by doing this instead:
const {
participant,
title,
department,
urgency,
assignmentBegin,
assignmentEnd,
description,
} = req.body;
await Assignment.create({
title: title,
department: department,
urgency: urgency,
assignmentBegin: assignmentBegin,
assignmentEnd: assignmentEnd,
description: description
}).then(async result => {
result.addUsers(participant)
}).catch(err => {
res.json({ message: "ERROR WHILE CREATING ASSIGNMENT!" });
console.log(">>> ERROR WHILE CREATING ASSIGNMENT!")
});
Hope this helps, if not lmk ill try to help some more.

Sequelize - is it possible to limit the number of record in junction table

There are 3 tables student_teacher, student, teacher with below relationship.
Each teacher will be responsible for 5 students, so the relationship should be 1 to Many, but I decide to create a junction table for storing extra information for this relationship.
When I create a student_teacher record, the payload will be like this:
{
"studentId": "xxx",
"teacherId": "yyy",
"groupName": "Group A"
}
Let's say I have record below now in table student_teacher:
[
{
"studentId": "studentA",
"teacherId": "teacherA",
"groupName": "Group X"
},
{
"studentId": "studentB",
"teacherId": "teacherA",
"groupName": "Group X"
},
{
"studentId": "studentC",
"teacherId": "teacherA",
"groupName": "Group X"
},
{
"studentId": "studentD",
"teacherId": "teacherA",
"groupName": "Group X"
},
{
"studentId": "studentE",
"teacherId": "teacherA",
"groupName": "Group X"
}
]
There are already 5 record for teacherA in table student_teacher, I will to forbid to create 1 more record for teacherA.
Is it possible to do it in Sequelize? Or handle I need to handle it in node.js function?
student-teacher.model.js
const Sequelize = require('sequelize');
const DataTypes = Sequelize.DataTypes;
module.exports = function (app) {
const sequelizeClient = app.get('sequelizeClient');
const studentTeacher = sequelizeClient.define('student_teacher', {
id: {
allowNull: false,
primaryKey: true,
type: DataTypes.UUID,
defaultValue: Sequelize.UUIDV4,
},
studentId: {
allowNull: false,
type: DataTypes.UUID,
references: { model: 'student', key: 'id' },
defaultValue: Sequelize.UUIDV4,
unique: 'studentId_foreign_idx'
},
teacherId: {
allowNull: false,
type: DataTypes.UUID,
references: { model: 'teacher', key: 'id' },
defaultValue: Sequelize.UUIDV4,
unique: 'teacherId_foreign_idx'
},
groupName: {
type: DataTypes.STRING,
allowNull: false,
defaultValue: ''
},
...
}, {
hooks: {
beforeCount(options) {
options.raw = true;
}
}
});
studentTeacher.associate = function (models) {};
return studentTeacher;
};
student.model.js
const Sequelize = require('sequelize');
const DataTypes = Sequelize.DataTypes;
module.exports = function (app) {
const sequelizeClient = app.get('sequelizeClient');
const student = sequelizeClient.define('student', {
id: {
allowNull: false,
primaryKey: true,
type: DataTypes.UUID,
defaultValue: Sequelize.UUIDV4,
},
email: {
type: DataTypes.STRING,
allowNull: false,
isEmail: true,
unique: 'email'
},
firstName:{
type: DataTypes.STRING,
allowNull: false,
defaultValue: '',
},
lastName:{
type: DataTypes.STRING,
allowNull: false,
defaultValue: '',
}
}, {
hooks: {
beforeCount(options) {
options.raw = true;
}
}
});
student.associate = function (models) {
student.belongsToMany(models.teacher, { as: 'teachers', through: 'student_teacher', foreignKey: 'studentId', onDelete: 'cascade' })
};
return student;
};
teacher.model.js
const Sequelize = require('sequelize');
const DataTypes = Sequelize.DataTypes;
module.exports = function (app) {
const sequelizeClient = app.get('sequelizeClient');
const teacher = sequelizeClient.define('teacher', {
id: {
allowNull: false,
primaryKey: true,
type: DataTypes.UUID,
defaultValue: Sequelize.UUIDV4,
},
email: {
type: DataTypes.STRING,
allowNull: false,
}
}, {
hooks: {
beforeCount(options) {
options.raw = true;
}
}
});
teacher.associate = function (models) {
teacher.belongsToMany(models.student, { as: 'students', through: 'student_teacher', foreignKey: 'teacherId', onDelete: 'cascade' })
};
return teacher;
};
Sequelize's hooks are very compatible with your requirement:
// in your student-teacher.model.js model (before you return the model)
studentTeacher.beforeCreate(async (instance, options) => {
try {
const result = await studentTeacher.findAll({
where: {
teacherId: instance.teacherId
}
});
if(result.length === MAX_RECORDS_FOR_TEACHER) {
throw new Error(`Cannot create more instnaces for ${instance.teacherId}`);
}
}
catch(e) {
throw e; // You must throw an error inside the hook in order to cancel
// the real statement execution.
}
});
Read more: https://sequelize.org/master/manual/hooks.html

No Sequelize instance passed for discordjs

https://github.com/qaiswaz/ticket
hear is the code please help me I've bean searching for a solution for a week now.
every time i try to run the bot hear is what it says
bot is online
Executing (default): SELECT 1+1 AS result
connected to DB
Error: No Sequelize instance passed
at Function.init (C:\Users\qaisw\OneDrive\Desktop\ALL FILES\discording\ticket\node_modules\sequelize\lib\model.js:921:13)
at Function.init (C:\Users\qaisw\OneDrive\Desktop\ALL FILES\discording\ticket\models\TicketConfig.js:5:20)
at C:\Users\qaisw\OneDrive\Desktop\ALL FILES\discording\ticket\bot.js:13:22
at processTicksAndRejections (internal/process/task_queues.js:88:5)
bot.js
require('dotenv').config();
const { Client } = require('discord.js');
const client = new Client({ partials: ['MESSAGE', 'REACTION'] });
const db = require('./database');
const Ticket = require('./models/Ticket');
const TicketConfig = require('./models/TicketConfig');
client.once('ready', () => {
console.log('bot is online');
db.authenticate()
.then(() => {
console.log('connected to DB');
Ticket.init(db);
TicketConfig.init(db);
Ticket.sync();
TicketConfig.sync();
}).catch((err) => console.log(err));
});
client.on('message', async message => {
if (message.author.bot || message.channel.type === 'dm') return;
if (message.content.toLowerCase() ==='?setup' && message.guild.ownerID === message.author.id) {
try {
const filter = (m) => m.author.id === message.author.id;
message.channel.send('please enter the message id for this ticket');
const msgId = (await message.channel.awaitMessages(filter, { max: 1})).first().content;
console.log(msgId)
const fetchMsg = message.channel.messages.fetch(msgId);
message.channel.send('please enter the category id for this ticket');
const categoryId = (await message.channel.awaitMessages(filter, { max: 1})).first().content;
console.log(categoryId)
const categoryChannel = client.channels.catche.get(categoryId);
message.channel.send('please enter all of the roles that have access to tickets');
const roles = (await message.channel.awaitMessages(filter, {max: 1})).first().content.split(/,\s*/);
if (fetchMsg && categoryChannel) {
for (const roleId of roles)
if (!message.guild.roles.cache.get(roleId)) throw new Error('role does not exist');
const ticketConfig = await TicketConfig.create({
messageId: msgId,
guildId: message.guild.id,
roles: json.stringify(roles),
parentId: categoryChannel.id
});
message.channel.send('saved config to db');
}else throw new error('invaild fields');
}catch (err) {
}
}
});
client.login(process.env.BOT_TOKEN);
database.js
const { Sequelize } = require('sequelize');
module.exports = new Sequelize(process.env.DB_NAME, process.env.DB_USER, process.env.DB_PASS, {
dialect: 'mysql',
host: process.env.DB_HOST
});
*models/Ticket.js
const { DataTypes, Model } = require('sequelize');
module.exports = class Tickets extends Model {
static init(sequelize) {
return super.init( {
ticketId: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true,
},
channelId: {
type: DataTypes.STRING,
},
guildId: {
type: DataTypes.STRING,
},
resolved:{
type: DataTypes.BOOLEAN,
},
closedMessageId:{
type: DataTypes.STRING,
},
authorId:{
type: DataTypes.STRING,
},
},
{
sequelize: sequelize,
modelName: 'Ticket'
})
}
}
models/TicketConfig.js
const { DataTypes, Model } = require('sequelize');
module.exports = class TicketConfig extends Model {
static init(sequelize) {
return super.init({
messegeId: {
type: DataTypes.STRING,
primaryKey: true
},
guildld: {
type: DataTypes.STRING
},
roles: {
type: DataTypes.STRING
},
parentld: {
type: DataTypes.STRING
},
sequelize: sequelize,
modelName: 'TicketConfig',
})
}
}
I added sequelizeInstance while define model
*models/Ticket.js
const { DataTypes, Model } = require('sequelize');
const sequelizeInstance = require('./database');
module.exports = class Tickets extends Model {
static init(sequelize) {
return super.init( {
ticketId: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true,
},
channelId: {
type: DataTypes.STRING,
},
guildId: {
type: DataTypes.STRING,
},
resolved:{
type: DataTypes.BOOLEAN,
},
closedMessageId:{
type: DataTypes.STRING,
},
authorId:{
type: DataTypes.STRING,
},
},
{
sequelize: sequelizeInstance, // <-
modelName: 'Ticket'
})
}
}
models/TicketConfig.js
const { DataTypes, Model } = require('sequelize');
const sequelizeInstance = require('./database')
module.exports = class TicketConfig extends Model {
static init(sequelize) {
return super.init({
messegeId: {
type: DataTypes.STRING,
primaryKey: true
},
guildld: {
type: DataTypes.STRING
},
roles: {
type: DataTypes.STRING
},
parentld: {
type: DataTypes.STRING
},
sequelize: sequelizeInstance, // <-
modelName: 'TicketConfig',
})
}
}

Sequelize association cant work on my code,please

im recently to sequelize.
I have 2 table, data_track and car_detail. i want to try associate that 2 table but it never associated.
it's always return error
SequelizeEagerLoadingError: car_detail is not associated to data_track!
please help me
both table have same primary key column name
data_track.js
const Sequelize = require('sequelize')
const gps_status_track = require("./../../configs/gps_status_track")
const data_track = gps_status_track.define('data_track',
{
car_id:{
type:Sequelize.INTEGER,
primaryKey:true
},
off_time:{
type:Sequelize.INTEGER,
},
nopol:{
type:Sequelize.STRING
},
wilayah:{
type:Sequelize.STRING
},
status:{
type:Sequelize.STRING
},
o_path:{
type:Sequelize.STRING
},
keterangan:{
type:Sequelize.STRING
},
last_update:{
type:"TIMESTAMP"
},
},
{
createdAt:'created_at',
updatedAt:'updated_at',
deletedAt:'deleted_at',
freezeTableName: true,
}
)
data_track.associate = (models)=>{
data_track.belongsTo(models.car_detail,{foreignKey:'car_id',as:'dataTrack'})
}
module.exports = data_track
car_detail.js
const Sequelize = require('sequelize')
const gps_status_track = require("./../../configs/gps_status_track")
const car_detail = gps_status_track.define('car_detail',
{
car_id:{
type:Sequelize.INTEGER,
primaryKey:true
},
nopol:{
type:Sequelize.STRING
},
wilayah:{
type:Sequelize.STRING
},
o_path:{
type:Sequelize.STRING
},
},
{
createdAt:'created_at',
updatedAt:'updated_at',
deletedAt:'deleted_at',
freezeTableName: true,
}
)
car_detail.associate = (models)=>{
car_detail.hasOne(models.data_track,{foreignKey:'car_id',as:'carDetail'})
}
module.exports = car_detail
Thanks!
Try doing it this way:
DataTrack.js:
module.exports = (sequelize, Sequelize) => {
const DataTrack = sequelize.define('data_track',
{
car_id: {
type: Sequelize.INTEGER,
primaryKey: true
},
off_time: {
type: Sequelize.INTEGER,
},
nopol: {
type: Sequelize.STRING
},
wilayah: {
type: Sequelize.STRING
},
status: {
type: Sequelize.STRING
},
o_path: {
type: Sequelize.STRING
},
keterangan: {
type: Sequelize.STRING
},
last_update: {
type: "TIMESTAMP"
},
},
{
createdAt: 'created_at',
updatedAt: 'updated_at',
deletedAt: 'deleted_at',
freezeTableName: true,
});
return DataTrack;
}
CarDetail.js:
module.exports = (sequelize, Sequelize) => {
const CarDetail = sequelize.define('car_detail',
{
car_id: {
type: Sequelize.INTEGER,
primaryKey: true
},
nopol: {
type: Sequelize.STRING
},
wilayah: {
type: Sequelize.STRING
},
o_path: {
type: Sequelize.STRING
},
},
{
createdAt: 'created_at',
updatedAt: 'updated_at',
deletedAt: 'deleted_at',
freezeTableName: true,
}
);
return CarDetail;
}
db.config.js:
const env = require('./env.js')
const Sequelize = require('sequelize')
const sequelize = new Sequelize(env.database, env.username, env.password, {
host: env.host,
dialect: env.dialect
})
const db = {}
db.Sequelize = Sequelize
db.sequelize = sequelize
db.data_track = require('../models/DataTrack')(sequelize, Sequelize)
db.car_detail = require('../models/CarDetail')(sequelize, Sequelize)
db.car_detail.hasOne(db.data_track, { foreignKey: { name: 'cars_id', allowNull: false } })
db.data_track.belongsTo(db.car_detail, { foreignKey: { name: 'cars_id', allowNull: false } })
module.exports = db
You're defining association is not correct.
car_detail.hasOne(models.data_track,{foreignKey:'carIDFK', sourceKey: 'cardDetailPKId', as:'carDetail'})
In the data track model, the association will look like.
data_track.belongsTo(models.car_detail,{foreignKey:'carIDFK', targetKey: 'cardDetailTablePKId'})