I'm trying to make this connection between these two tables, but I'm not getting it and it's giving the following error: "UnhandledPromiseRejectionWarning: SequelizeEagerLoadingError: cfg_user is not associated to dn_coluna!"
follows below the controllers and models that I am using to inner join
This is my cfg_user.js
const sequelizePaginate = require("sequelize-paginate");
module.exports = function(sequelize, DataTypes) {
const cfg_user = sequelize.define("cfg_user", {
'id_cfg_user': {
type: DataTypes.INTEGER(11),
allowNull: false,
primaryKey: true,
autoIncrement: true
},
'id_cfg_grupo': {
type: DataTypes.INTEGER(11),
allowNull: true
},
'nome': {
type: DataTypes.CHAR(100),
allowNull: true
},
'email': {
type: DataTypes.CHAR(100),
allowNull: true
},
'arquivo': {
type: DataTypes.CHAR(255),
allowNull: false
},
'senha': {
type: DataTypes.CHAR(32),
allowNull: true
}
},{
tableName: "cfg_user",
freezeTableName: true,
timestamps: false
});
sequelizePaginate.paginate(cfg_user);
return cfg_user;
};
This is my dn_coluna.js
const sequelizePaginate = require("sequelize-paginate");
const cfg_user = require("./cfg_user");
module.exports = function(sequelize, DataTypes) {
const dn_coluna = sequelize.define("dn_coluna", {
'id_dn_coluna': {
type: DataTypes.INTEGER(10),
allowNull: false,
primaryKey: true,
autoIncrement: true
},
'id_cfg_user': {
type: DataTypes.INTEGER(10),
allowNull: false
},
'coluna': {
type: DataTypes.CHAR(255),
allowNull: false
},
'frase': {
type: DataTypes.CHAR(255),
allowNull: true,
},
'resumo': {
type: DataTypes.CHAR(255),
allowNull: true,
},
'url': {
type: DataTypes.CHAR(255),
allowNull: true
},
'arquivo': {
type: DataTypes.CHAR(255),
allowNull: true
},
'arquivo_topo': {
type: DataTypes.CHAR(255),
allowNull: true
},
'arquivo_bg': {
type: DataTypes.CHAR(255),
allowNull: true
},
'ordem': {
type: DataTypes.INTEGER(11),
allowNull: true
},
'destaque':{
type: DataTypes.TINYINT(1),
allowNull: true
},
'libera': {
type: DataTypes.TINYINT(1),
allowNull: true
}
},{
tableName: "dn_coluna",
freezeTableName: true,
timestamps: false
});
sequelizePaginate.paginate(dn_coluna);
return dn_coluna;
};
this is my Controller
const { dn_coluna } = require("../models");
const { cfg_user } = require("../models");
module.exports = {
async index(req, res){
const colunas = await dn_coluna.findAll({
include: [{
model: cfg_user,
attributes: []
}],
attributes: ['id_cfg_user'],
})
.then(colunas => {
return res.status(200).json(colunas);
});
},
};
Your answer lies in associations. You are not properly associating your tables together. Here is a link to the documentation. I am unsure of the type of relationship that cfg_user and dn_coluna have so I can't show you how to write the association but the below may help.
Remove the below from dn_coluna.js
'id_cfg_user': {
type: DataTypes.INTEGER(10),
allowNull: false
}
Add in to dn_coluna.js (just above sequelizePaginate.paginate(dn_coluna);):
dn_coluna.associate = (models) => {
dn_coluna.hasMany(models.cfg_user, {foreignKey: 'cfg_user_id'})
}
In cfg_user.js add (just above sequelizePaginate.paginate(cfg_user);):
cfg_user.associate = (models) => {
cfg_user.belongsTo(models.dn_coluna)
}
The above will create a one to many relationship between dn_coluna and cfg_user.
Related
I have two tables, Post and Comments, I am trying to get all posts by userId and also fetch the relevant comments for each post using the following code. I am getting all the posts but nodejs through an error " comment is not associated to post".
Post Table
const {Sequelize, DataTypes} = require('sequelize')
const db = require('../config/db')
const Post = db.define('post', {
id:{
type: DataTypes.INTEGER(255),
autoIncrement: true,
allowNull: false,
primaryKey: true
},
postId:{
type: DataTypes.UUID,
defaultValue: Sequelize.UUIDV4
},
postText:{
type: DataTypes.TEXT,
allowNull: false
},
totalPostLikes: {
type: DataTypes.INTEGER,
allowNull: true,
defaultValue: 0
},
totalPostStrikes: {
type: DataTypes.INTEGER,
allowNull: true,
defaultValue: 0
},
totalPostQuotes: {
type: DataTypes.INTEGER,
allowNull: true,
defaultValue: 0
},
totalPostShare: {
type: DataTypes.INTEGER,
allowNull: true,
defaultValue: 0
},
userId:{
type: DataTypes.INTEGER,
allowNull: false,
references: {
model: 'users',
key: 'id'
}
}
},{
freezeTableName: true
})
module.exports = Post
Comments Table
const {Sequelize, DataTypes} = require('sequelize')
const db = require('../config/db')
const Comment = db.define('comment', {
id:{
type: DataTypes.INTEGER(255),
autoIncrement: true,
allowNull: false,
primaryKey: true
},
commentUUID:{
type: DataTypes.UUID,
defaultValue: Sequelize.UUIDV4
},
commentText:{
type: DataTypes.TEXT,
allowNull: false
},
totalCommentLikes: {
type: DataTypes.INTEGER,
allowNull: true,
defaultValue: 0
},
totalCommentStrikes: {
type: DataTypes.INTEGER,
allowNull: true,
defaultValue: 0
},
totalCommentQuotes: {
type: DataTypes.INTEGER,
allowNull: true,
defaultValue: 0
},
userId:{
type: DataTypes.INTEGER,
allowNull: false,
references: {
model: 'users',
key: 'id'
}
}, postId:{
type: DataTypes.INTEGER,
allowNull: false,
references: {
model: 'post',
key: 'id'
}
}
},{
freezeTableName: true
})
module.exports = Comment
This is how I am creating tables and associations
const db = require('../config/db')
const User = require('./user')
const Post = require('./posts')
const Comments = require('./comments')
User.hasMany(Post)
Post.belongsTo(User)
Post.hasMany(Comments)
Comments.belongsTo(Post)
User.hasMany(Comments)
Comments.belongsTo(User)
db.sync({force: true})
.then((result) =>{
console.log(result)
})
.catch((error) => {
console.log(error)
})
Code to fetch data
router.get('/:id', authenticate, async (req,res) => {
const { id } = req.params
const data = await Post.findAll(
{where: {userId: id},
attributes: [
'postText',
'totalPostLikes',
'totalPostStrikes',
'totalPostQuotes',
'totalPostShare'
],
include:[{model: Comments, attributes:['commentText']}]
})
try{
res.send(data);
} catch({errors}) {
res.status(400).send(errors)
}
})
const Sequelize = require('sequelize');
const Op = Sequelize.Op;
const db = require('../models');
var main = async () => {
try {
const data = await db.post.findAll({
where: { userId: 1 },
attributes: ['postText', 'totalPostLikes', 'totalPostStrikes', 'totalPostQuotes', 'totalPostShare'],
include: [{ model: db.comment, attributes: ['commentText'], as: 'comments' }],
});
console.log(JSON.parse(JSON.stringify(data)));
} catch (e) {
console.log(e);
}
};
main();
I tried to create database with 3 tables: restaurant,restaurant_menu,menu and their relationship is restaurant have many menu and menu can belong to many restarant by sequelize in Nodejs.
restaurant.model.js
'use strict';
module.exports = (sequelize, DataTypes) => {
const restaurant = sequelize.define('restaurant', {
id: {
type: DataTypes.INTEGER,
allowNull: false,
autoIncrement: true,
primaryKey: true
},
name: DataTypes.STRING,
address: DataTypes.STRING,
phone: DataTypes.STRING,
lat: {
type: DataTypes.DOUBLE,
allowNull: false,
defaultValue: 0
},
lng: {
type: DataTypes.DOUBLE,
allowNull: false,
defaultValue: 0
},
user_owner: {
type: DataTypes.INTEGER,
defaultValue: 0
},
image: {
type: DataTypes.TEXT,
allowNull: false
},
payment_url: {
type: DataTypes.TEXT,
allowNull: false
}
}, {
freezeTableName: true,
timestamps: false
});
restaurant.associate = function (models) {
// associations can be defined here
restaurant.belongsToMany(models.menu, {
through: {
model: models.restaurant_menu
},
foreignKey: 'restaurant_id'
})
};
return restaurant;
};
menu.model.js
'use strict';
module.exports = (sequelize, DataTypes) => {
const menu = sequelize.define('menu', {
id: {
type: DataTypes.INTEGER,
primaryKey: true,
allowNull: false
},
name: DataTypes.STRING(50),
description: DataTypes.STRING(500),
image: DataTypes.TEXT
}, {
freezeTableName: true,
timestamps: false
});
menu.associate = function (models) {
// associations can be defined here
menu.belongsToMany(models.restaurant, {
through: {
model: models.restaurant_menu
},
foreignKey: "menu_id"
});
};
return menu;
};
restaurant_menu.model.js
'use strict';
module.exports = (sequelize, DataTypes) => {
const restarant_menu = sequelize.define('restarant_menu', {
restaurant_id: {
type: DataTypes.INTEGER,
primaryKey: true,
allowNull: false,
references: {
model: 'restaurant'
}
},
menu_id: {
type: DataTypes.INTEGER,
primaryKey: true,
allowNull: false,
references: {
model: 'menu'
}
}
}, {
freezeTableName: true,
timestamps: false
});
restarant_menu.associate = function (models) {
// associations can be defined here
};
return restarant_menu;
};
i tried to run migration, but i get error:
Cannot read property 'menu_id' of undefined
How can I fix it?
I believe you are writing old syntax, checkout documentation.
https://sequelize.org/master/manual/advanced-many-to-many.html
I am considering these 2 tables "exam_response" and "answer" for hasMany association.
Where both the tables contains "question_id". Using question_id I need the answers.
exam_response table
module.exports = (sequelize, DataTypes) => {
const exam_response = sequelize.define('exam_response', {
id: {
allowNull: false,
primaryKey: true,
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4
},
session_id: {
type: DataTypes.UUID,
allowNull: false
},
exam_id: {
type: DataTypes.UUID,
allowNull: false
},
user_id: {
type: DataTypes.UUID,
allowNull: false
},
question_id: {
type: DataTypes.UUID,
allowNull: false
},
answer_ids: {
type: DataTypes.ARRAY(DataTypes.UUID),
allowNull: false
},
is_correct: {
type: DataTypes.BOOLEAN,
allowNull: false
},
is_bookmarked: {
type: DataTypes.BOOLEAN,
allowNull: false
},
is_attempted: {
type: DataTypes.BOOLEAN,
allowNull: false
},
createdAt: {
type: DataTypes.DATE,
field: 'created_at'
},
updatedAt: {
type: DataTypes.DATE,
field: 'updated_at'
}
}, {});
exam_response.associate = function (models) {
// associations can be defined here
exam_response.hasMany(models.answer, {
foreignKey: 'question_id', sourceKey: 'question_id',as:'exam_answers'
});
};
answer table
'use strict';
module.exports = (sequelize, DataTypes) => {
const answer = sequelize.define('answer', {
//{
// "id":"",
// "question_id":"123",
// "position":0,
// "answer":"This is answer 1."
// }
id: {
allowNull: false,
primaryKey: true,
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4
},
question_id: {
allowNull: false,
type: DataTypes.UUID
},
position: {
allowNull: false,
type: DataTypes.INTEGER
},
answer: {
allowNull: false,
type: DataTypes.TEXT
},
publish_status: {
allowNull: false,
type: DataTypes.ENUM('published', 'unpublished', 'deleted')
},
language: {
type: DataTypes.ENUM('en', 'kn', 'hi')
},
createdAt: {
type: DataTypes.DATE,
field: 'created_at'
},
updatedAt: {
type: DataTypes.DATE,
field: 'updated_at'
}
}, {});
answer.associate = models => {
answer.belongsTo(models.question,{foreignKey:'question_id',as:'answers'});
answer.belongsTo(models.exam_response,{foreignKey:'question_id', targetKey: 'question_id',as:'exam_answers'});
};
return answer;
};
Query::
ExamResponse.findAll({
where: {
exam_id
},
include: [
{
model: Answer,as:'exam_answers'
}
],
}).then(resp => {
response.successGet(res, resp, 'Exam Response');
}).catch(next)
I am getting the output but associated part("exam_answers") is empty.
If I use raw query, i am able to get the output. But the Query is only fetching me the exam_response not the answer even though the value exists.
I am trying to create an association in sequelize 4, table is getting created but the foreign key reference is not happening.
const Sequelize = require("sequelize");
const db = require("../config/db.js");
const ValidationList = require("./validation_list.js");
const AppList = db.define("app_list", {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
application: {
type: Sequelize.STRING,
allowNull: false
},
environment: {
type: Sequelize.STRING,
allowNull: false
},
instance_name: {
type: Sequelize.STRING,
allowNull: false
},
url: {
type: Sequelize.STRING,
allowNull: true
}
});
AppList.associate = function (models) {
AppList.belongsTo(models.ValidationList, {
foreignKey: 'application',
targetKey: 'application_name'
});
};
module.exports = AppList;
Is it something am doing wrong here?
model validation_list.js is also similar to app_list.js
const db = require("../config/db.js");
const Sequelize = require("sequelize");
const ValidationList = db.define("validation_list", {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
os: {
type: Sequelize.STRING,
allowNull: true
},
caac_folder_id: {
type: Sequelize.STRING,
allowNull: false
},
application_name: {
type: Sequelize.STRING,
allowNull: false,
unique: true
}
});
module.exports = ValidationList;
Here is the validation_list model.
I was wandering if there are any extended tutorials on how to save a many to many relationship? I find the documentation more than basic. Its missing many use case examples.
I have two models: Client and Rule. They have the n:n relationship.
Client:
var Client = sequelize.define('client', {
title: {
type: DataTypes.STRING(200),
allowNull: false
},
company: {
type: DataTypes.STRING(200),
allowNull: false
},
vendor: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false
},
consumer: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: true
},
address_id: {
type: DataTypes.INTEGER,
allowNull: true
}
},{
paranoid: true,
underscored: true,
classMethods: {
associate:function(models){
Client.hasMany(models.rule, { through: 'client_rules', onDelete: 'cascade'});
}
}
});
Rule:
var Rule = sequelize.define('rule', {
service_id: {
type: DataTypes.INTEGER,
allowNull: false
},
is_allowed: {
type: DataTypes.BOOLEAN,
defaultValue: false
},
valid_until: {
type: DataTypes.DATE,
allowNull: true,
},
rule: {
type: DataTypes.TEXT,
allowNull: true
},
type: {
type: DataTypes.INTEGER, // 1 for company rule, 2 for individual rule
allowNull: false,
},
active: {
type: DataTypes.BOOLEAN,
defaultValue: true
}
},{
underscored: true,
paranoid: true,
classMethods: {
associate:function(models){
Rule.belongsToMany(models.client, { through: 'client_rules', onDelete: 'cascade'});
Rule.belongsTo(models.service, { foreignKey: 'service_id' } );
}
}
});
Now I would like to create a new rule for client. So I would have to create the rule first and associate it then to the client through 'client_rules'.
How do I do that with sequelize? This doesn't work:
var clientID = req.user.client_id;
Client.find({ id: clientID })
.then(function(client){
return client.addRule(req.body)
})
.catch(function(err){
console.log(err)
})
[TypeError: Cannot read property 'replace' of undefined]
Ok I found out how to do it. The docs are very confusing.
var clientID = req.user.client_id;
return Rule.create(req.body)
.then(function(newRule){
var ruleToAdd = newRule;
return Client.findOne({ where: { id: clientID } })
.then(function(client){
return client.addRule(ruleToAdd)
.then(function(ans){
return ruleToAdd;
})
})