Nodejs Sequelize belongsToMany not working - javascript

I dont know why I am getting this error error: SequelizeDatabaseError: Unknown column 'student-> section ->grademapping.studentId' in 'field list' I just follow this documentation on how to use belongsToMany did i miss something on the documentation? https://sebhastian.com/sequelize-belongstomany/
let student = await Database.getConnection().models.Student;
let grademapping = await Database.getConnection().models.Grademapping;
let section = await Database.getConnection().models.Section;
let taxtypemapping = await student.findAll({
attributes:['_id','FirstName','LastName', 'section.Description'],
include:[
{ model: section, attribute:[] }
],
raw: true
})
the models
class taxtypedetails extends Sequelize.Model {}
Section.init(
{
_id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true,
},
Description: {
type: Sequelize.STRING,
},
},
{ sequelize, tableName: 'section', timestamps: false },
)
class Student extends Sequelize.Model {}
Student.init(
{
_id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true,
},
FirstName: {
type: Sequelize.STRING,
},
LastName: {
type: Sequelize.STRING,
},
},
{ sequelize, tableName: 'student', timestamps: false },
)
class Grademapping extends Sequelize.Model {}
Grademapping.init(
{
_id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true,
},
sectionID: {
type: Sequelize.INTEGER,
references: {
model: 'section',
key: '_id',
},
},
studentID: {
type: Sequelize.INTEGER,
references: {
model: 'student',
key: '_id',
},
}
},
{ sequelize, tableName: 'grademapping', timestamps: false },
)
student.belongsToMany(section,{through: grademapping})
section.belongsToMany(student,{through: grademapping})

Related

Sequelize M:N Association - "TypeError: Members.belongsToMany is not a function"

I have two tables in a MySQL schema, 'members' and 'events', which share a many-to-many relationship. I am attempting to model that relationship using Sequelize via a junction table containing a member_id and an event_id (which correspond to columns in the Members and Events tables respectively) and an event_date - the date when an event is attended by many members.
I am following the guidance in the Sequelize 'Advanced Associations' section (link), but am getting an error when my node.js server attempts to start, as follows:
Members.belongsToMany(models.Events, { through: 'member_events' })
^
TypeError: Members.belongsToMany is not a function
I'm really stuggling to understand what specifically this means and how I can address the issue. The following is my code for the three models in question:
memberEvents.js
module.exports = (sequelize, DataTypes) => {
const Members = require('../models/members')
const Events = require('../models/events')
const MemberEvents = sequelize.define(
"MemberEvents",
{
member_id: {
type: DataTypes.INTEGER,
allowNull: false,
primaryKey: true,
},
event_id: {
type: DataTypes.INTEGER,
allowNull: false,
primaryKey: true,
},
event_date: {
type: DataTypes.DATEONLY,
allowNull: false,
primaryKey: true,
},
},
{ tableName: "member_events" }
);
Members.belongsToMany(Events, { through: 'member_events' })
Events.belongsToMany(Members, { through: 'member_events' })
return MemberEvents;
};
Members.js
module.exports = (sequelize, DataTypes) => {
//Below creates the member table in the schema
const Members = sequelize.define(
"Members",
{
member_id: {
type: DataTypes.INTEGER,
autoIncrement: true,
allowNull: false,
primaryKey: true,
},
forename: {
type: DataTypes.STRING(35),
allowNull: false,
},
surname: {
type: DataTypes.STRING(35),
allowNull: false,
},
date_of_birth: {
type: DataTypes.DATEONLY,
allowNull: false,
},
address_1: {
type: DataTypes.STRING(35),
allowNull: false,
},
address_2: {
type: DataTypes.STRING(35),
},
address_3: {
type: DataTypes.STRING(35),
},
address_4: {
type: DataTypes.STRING(35),
},
address_5: {
type: DataTypes.STRING(35),
},
postcode: {
type: DataTypes.STRING(12),
allowNull: false,
},
directions: {
type: DataTypes.TEXT("long"),
},
mobile_phone: {
type: DataTypes.STRING(12),
},
email_address: {
type: DataTypes.STRING(255),
},
key_safe_code: {
type: DataTypes.STRING(8),
},
next_of_kin_name: {
type: DataTypes.STRING(70),
},
next_of_kin_phone: {
type: DataTypes.STRING(12),
},
next_of_kin_local: {
type: DataTypes.STRING(33),
},
next_of_kin_relationship: {
type: DataTypes.STRING(40),
},
doctor_name: {
type: DataTypes.STRING(35),
},
initial_medical_conditions: {
type: DataTypes.TEXT("long"),
},
deceased: {
type: DataTypes.DATEONLY,
},
normally_escorted: {
type: DataTypes.STRING(3),
},
blue_badge_holder: {
type: DataTypes.STRING(3),
},
medical_equipment: {
type: DataTypes.STRING,
},
},
{ tableName: "Member" }
);
return Members;
};
Events.js
module.exports = (sequelize, DataTypes) => {
//Below creates the event table in the schema
const Events = sequelize.define(
"Events",
{
event_id: {
type: DataTypes.INTEGER,
autoIncrement: true,
allowNull: false,
primaryKey: true,
},
event_name: {
type: DataTypes.STRING(70),
allowNull: false,
},
staff_id: {
type: DataTypes.INTEGER,
allowNull: false,
},
},
{ tableName: "Events" }
);
return Events;
};
When separating your Sequelize models into separate imports, use the associate function to access the models to make these associations. You also don't need to import the other models into each other.
Something along these lines should work:
TableA.js
module.exports = (sequelize, DataTypes) => {
const TableA = sequelize.define('table_a', {
foobar: DataTypes.STRING,
}, {});
TableA.associate = function(models) {
TableA.belongsTo(models.TableB, { through: 'table_c' });
};
return TableA;
};
TableB.js
module.exports = (sequelize, DataTypes) => {
const TableB = sequelize.define('table_b', {
fazbaz: DataTypes.STRING,
}, {});
TableB.associate = function(models) {
TableB.belongsTo(models.TableA, { through: 'table_c' });
};
return TableB;
};

How create (optimize) service on Backend (ExpressJS) with sequelize

Tried to create API for internet store using ExpressJS and sequelize. I have users, basket and devices. To connect basket and choosen by user devices used middle table BasketDevice.
Models:
export const Models = {
User: sequelize.define('user',
{
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
email: { type: DataTypes.STRING, unique: true },
password: { type: DataTypes.STRING },
role: { type: DataTypes.STRING, defaultValue: 'USER' },
isActivated: { type: DataTypes.BOOLEAN, defaultValue: false},
activationLink: { type: DataTypes.STRING, unique: true }
}
),
Basket: sequelize.define('basket',
{
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
}
),
BasketDevice: sequelize.define('basketDevice',
{
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
}
),
Device: sequelize.define('device',
{
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
name: { type: DataTypes.STRING, allowNull: false, unique: true },
price: { type: DataTypes.INTEGER, allowNull: false },
img: { type: DataTypes.STRING, allowNull: false },
rating: { type: DataTypes.INTEGER, defaultValue: 0 },
}
}
Assotiations between tables:
Models.User.hasOne(Models.Basket)
Models.Basket.belongsTo(Models.User)
Models.Basket.hasMany(Models.BasketDevice, {as: 'devices'})
Models.BasketDevice.belongsTo(Models.Basket)
Models.Device.hasMany(Models.BasketDevice)
Models.BasketDevice.belongsTo(Models.Device)
Tryed to give in response basket include basket device
Basket service:
class BasketService {
async getBasket(token: string) {
const userData = await TokenService.verifyRefreshToken(token) as any
const basket = await Models.Basket.findOne({
where: { userId: userData.id },
include: [{model: Models.BasketDevice, as: 'devices'}]
})
return basket
}
}
Don't know how create getBasket function that gives added to cart devices and counting of one device
What is the opltimal way to give devices added in basket?

Sequelize - Include based on specific attribute

I have a model defined as follows:
sequelize.define('game', {
id: {
type: type.INTEGER,
primaryKey: true,
autoIncrement: true,
},
leaderId: {
type: type.INTEGER,
allowNull: false,
references: {
model: 'users',
key: 'id',
},
},
playerId: {
type: type.INTEGER,
allowNull: false,
references: {
model: 'users',
key: 'id',
},
},
status: {
type: type.STRING,
defaultValue: 'running',
},
notes: {
type: type.TEXT,
},
});
I'm trying to use Sequelize to load all game object and include the User with the id equal to the playerId field.
The problem is I have two attributes (leaderId, playerId) which reference the User model so using include as follows does not work:
Game.findAll({
where: conditions,
include: [{ model: User }],
})
Is there a way to specify which attribute the include command should use?
const game = sequelize.define('game', {
id: {
type: type.INTEGER,
primaryKey: true,
autoIncrement: true,
},
leaderId: {
type: type.INTEGER,
allowNull: false,
references: {
model: 'users',
key: 'id',
},
},
playerId: {
type: type.INTEGER,
allowNull: false,
references: {
model: 'users',
key: 'id',
},
as:'player'
},
status: {
type: type.STRING,
defaultValue: 'running',
},
notes: {
type: type.TEXT,
},
});
game.associate = function (models) {
game.belongsTo(models.user, {
foreignKey: "playerId",
as: "player",
});
game.belongsTo(models.user, {
foreignKey: "leaderId",
as: "leader",
});
};
Game.findAll({
where: conditions,
include: ['player'],
})
Or
Game.findAll({
where: conditions,
include: [{model: User, as: 'player' }],
})
Or
Game.findAll({
where: conditions,
include: [{model: User, as: 'player', foreignKey: 'playerId' }],
})
https://github.com/nkhs/node-sequelize

Sequelize request error SequelizeEagerLoadingError

I’m new with sequelize I’m trying to make a request with associate tables
I have a first model called Experience
module.exports = function (sequelize, DataTypes) {
const Experience = sequelize.define('experience', {
internalId: {
type: DataTypes.BIGINT,
unique: true,
allowNull: false,
},
label: {
type: DataTypes.STRING,
unique: false,
allowNull: false,
},
picture: {
type: DataTypes.TEXT,
unique: false,
allowNull: true,
},
type: {
type: DataTypes.STRING,
validate: {
isIn: {
args: [[
'generic',
'specific',
]],
msg: 'Must be a valid type',
},
},
unique: false,
allowNull: true,
},
author: {
type: DataTypes.STRING,
unique: false,
allowNull: true,
defaultValue: 'import',
},
isActive: {
type: DataTypes.BOOLEAN,
defaultValue: true,
},
});
Experience.associate = (models) => {
Experience.belongsToMany(models.Tag, {
as: 'Tags',
through: models.ExperienceTag,
});
};
return Experience;
};
a second called Tags
module.exports = function (sequelize, DataTypes) {
const Tag = sequelize.define('tag', {
internalId: {
type: DataTypes.STRING,
unique: true,
allowNull: false,
},
name: {
type: DataTypes.STRING,
unique: false,
allowNull: false,
},
author: {
type: DataTypes.STRING,
unique: false,
allowNull: true,
defaultValue: 'import',
},
isActive: {
type: DataTypes.BOOLEAN,
defaultValue: true,
},
});
Tag.associate = (models) => {
Tag.belongsToMany(models.Experience, {
as: 'Experiences',
through: models.ExperienceTag,
});
};
return Tag;
};
The association table name was ExperienceTags
I would like get all the Experiencewho have a tagId = 44
This is my request:
Experience.findAll({
include: [{
model: ExperienceTag,
where: { tagId: 44 },
}],
})
.then((results) => {
winston.warn(JSON.stringify(results, null, 2));
res.status(200)
.send(results);
})
.catch(error => res.status(500)
.send({ error: error.toString() }));
But when I execute it I have an error like:
{
"error": "SequelizeEagerLoadingError: experienceTag is not associated to experience!"
}
I think you like to include Tag rather than ExperienceTag, the following example may help you
Experience.findAll({
include: [{
model: Tag, //model name which you want to include
as: 'Tags', // you have to pass alias as you used while defining
where: { tagId: 44 },
}],
})
I think , you need to add as: 'Experiences' , in your include as you have defined association with alias
Change this
Experience.findAll({
include: [{
model: ExperienceTag,
where: { tagId: 44 },
}],
})
With
Experience.findAll({
include: [{
model: ExperienceTag,
as: 'Experiences', // <---- HERE
where: { tagId: 44 },
}],
})

Sequelize.js - "is not associated to"

I have some issue with getting full data from db.
That are my models:
User
module.exports = function(sequelize, DataTypes) {
return sequelize.define('user', {
id: {
type: DataTypes.INTEGER(11),
allowNull: false,
primaryKey: true,
autoIncrement: true,
field: 'ID'
},
password: {
type: DataTypes.STRING(255),
allowNull: false,
field: 'password'
},
email: {
type: DataTypes.STRING(255),
allowNull: false,
unique: true,
field: 'email'
},
roleId: {
type: DataTypes.INTEGER(11),
allowNull: false,
references: {
model: 'role',
key: 'ID'
},
field: 'role_id'
}
}, {
timestamps: false,
tableName: 'user'
});
};
Role
module.exports = function(sequelize, DataTypes) {
return sequelize.define('role', {
id: {
type: DataTypes.INTEGER(11),
allowNull: false,
primaryKey: true,
autoIncrement: true,
field: 'ID'
},
name: {
type: DataTypes.STRING(255),
allowNull: false,
unique: true,
field: 'name'
},
description: {
type: DataTypes.STRING(255),
allowNull: false,
field: 'description'
},
permission: {
type: DataTypes.INTEGER(11),
allowNull: false,
field: 'permission'
}
}, {
timestamps: false,
tableName: 'role',
});};
I want to get object of one specific user including all role content.
Somethink like
{
id: 4,
password: 'xxx',
email: 'adsads#saas.com',
role: {
id: 2,
name: 'admin'
description: 'ipsum ssaffa',
permission: 30
}
}
So I'm using:
User.findOne( { where: { id: req.userId }, include: [ Role ] } ).then( user =>{...});
but I get in the result err.message: "role is not associated to user"
And the simple question - what's wrong ? :)
*to handle models I'm using sequelize-cli
You get this error because you didn't add associate between the models
base on your json I see that each user only has one role, so you can either use belongsTo in role model or hasOne in user model
Should be something like this:
User.js
module.exports = function(sequelize, DataTypes) {
var user = sequelize.define('user', {
id: {
type: DataTypes.INTEGER(11),
allowNull: false,
primaryKey: true,
autoIncrement: true,
field: 'ID'
},
password: {
type: DataTypes.STRING(255),
allowNull: false,
field: 'password'
},
email: {
type: DataTypes.STRING(255),
allowNull: false,
unique: true,
field: 'email'
},
roleId: {
type: DataTypes.INTEGER(11),
allowNull: false,
references: {
model: 'role',
key: 'ID'
},
field: 'role_id'
}
}, {
timestamps: false,
tableName: 'user'
});
user.associate = function(models) {
user.hasOne(models.role, {foreignKey: 'id',sourceKey: 'roleId'});
}
return user;
};
Role.js
module.exports = function(sequelize, DataTypes) {
var role = sequelize.define('role', {
id: {
type: DataTypes.INTEGER(11),
allowNull: false,
primaryKey: true,
autoIncrement: true,
field: 'ID'
},
name: {
type: DataTypes.STRING(255),
allowNull: false,
unique: true,
field: 'name'
},
description: {
type: DataTypes.STRING(255),
allowNull: false,
field: 'description'
},
permission: {
type: DataTypes.INTEGER(11),
allowNull: false,
field: 'permission'
}
}, {
timestamps: false,
tableName: 'role',
});
role.associate = function(models) {
user.belongsTo(models.role, {foreignKey: 'id'});
}
return role;
};
You have to declare associations between your Models. If using Sequelize CLI make sure the static method associate is being called. Example:
/models.index.js
const Category = require('./Category');
const Product = require('./Product');
const ProductTag = require('./ProductTag');
const Tag = require('./Tag');
Category.associate({Product});
Product.associate({Category,Tag});
Tag.associate({Product});
module.exports={Category,Product,ProductTag,Tag};
and then the association in Category.js
'use strict';
const {Model,DataTypes} = require('sequelize');
const sequelize = require('../config/connection.js');
class Category extends Model {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The `models/index` file will call this method.
*/
static associate({Product}) {
// define association here
console.log('Category associated with: Product');
this.hasMany(Product, {
foreignKey: 'category_id',
onDelete: 'CASCADE'
});
}
}
Category.init({
category_id: {type: DataTypes.INTEGER, autoIncrement: true, allowNull: false, primaryKey: true},
category_name: {type: DataTypes.STRING, allowNull: false}
}, {
sequelize,
timestamps: false,
freezeTableName: true,
underscored: true,
modelName: "Category",
});
module.exports = Category;

Categories