Sequelize hasMany association issue - mysql

In my application a user can have several module which is stored in the user_has_module table. This means that for each user_has_module row, I want to include module where the module_id matches.
module
Module = sequelize.define('module', {
academy_id: {
type: DataTypes.INTEGER,
primaryKey: true
},
module_id: {
type: DataTypes.INTEGER,
primaryKey: true
},
module_module_type_id: DataTypes.INTEGER,
sort_number: DataTypes.INTEGER,
score_to_pass: DataTypes.INTEGER
}, {
freezeTableName: true
})
user_has_module
User_has_module = sequelize.define('user_has_module', {
user_id: {
type: DataTypes.INTEGER,
primaryKey: true
},
module_id: {
type: DataTypes.INTEGER,
primaryKey: true
},
academy_team_id: {
type: DataTypes.INTEGER,
primaryKey: true
},
academy_id: {
type: DataTypes.INTEGER,
primaryKey: true
},
sort_number: DataTypes.INTEGER,
is_complete: DataTypes.INTEGER,
score_to_pass: DataTypes.INTEGER,
is_open: DataTypes.INTEGER,
deadline: DataTypes.DATE
}, {
freezeTableName: true
})
My relation
User_has_module.belongsTo(Module, {foreignKey: 'module_id'});
Now what I want to do is join them on module.module_id = user_has_module.module_id.
My problem is that module has, as you can see, two primary key, and when sequelize joins these two tables, it chooses academy_id as its primary key.
My question is, is there a way to tell Sequelize that in this relation it has to choose the primary key module_id from module?

I think you don't need a model called User_has_module.
I assume you have one model called User and one model call Module.
So you should have designed something like this:
var User = sequelize.define("User", {
name: DataTypes.STRING
}, {
classMethods: {
associate: function(models) {
User.hasMany(models.Module);
}
}
});
And for your Module:
var Module = sequelize.define("Module", {
name: DataTypes.STRING
}, {
classMethods: {
associate: function(models) {
Module.belongsToMany(models.User);
}
}
});
To get a User with its Modules you can do this:
models.User.findAll({ include: [models.Module]}).then(function(users){
console.log(users);
});
Hope I got your question right and it helps.
Cheers

Related

Sequelize M:N association not updating through table record

When I try to update a recipe with associated tags using the through option, no record is updated in the joining table in the mysql database I'm connected to.
Here are my models definitions:
export const Recipe = sequelize.define('Recipe', {
// Model attributes are defined here
title: {
type: DataTypes.STRING,
allowNull: false
},
image: {
type: DataTypes.STRING,
allowNull: true
},
prepTime: {
type: DataTypes.DOUBLE,
allowNull: false
},
cookTime: {
type: DataTypes.DOUBLE,
allowNull: false
},
totalTime: {
type: DataTypes.DOUBLE,
allowNull: false
},
servings: {
type: DataTypes.INTEGER,
allowNull: false
},
rating: {
type: DataTypes.INTEGER,
allowNull: false
},
notes: {
type: DataTypes.STRING, allowNull: true
},
}, {
// Other model options go here
tableName: 'Recipes'
});
export const Tag = sequelize.define('Tag', {
// Model attributes are defined here
name: {
type: DataTypes.STRING,
allowNull: false
},
}, {
// Other model options go here
tableName: 'Tags'
});
export const RecipeTag = sequelize.define('RecipeTag', {
// Model attributes are defined here
}, {
// Other model options go here
timestamps: false,
tableName: 'RecipeTags'
});
Here are my associations:
Recipe.belongsToMany(Tag, {
through: RecipeTag,
foreignKey: 'recipeId',
as: 'tags'
})
Tag.belongsToMany(Recipe, {
through: RecipeTag,
foreignKey: 'tagId',
as: 'recipes'
})
Here is the update call:
Recipe.update(args, {
include: [{
model: Tag,
through: RecipeTag,
as: 'tags',
where: {
recipeId: args.id
}
}],
where: {
id: args.id
},
});
Only one update mysql call is executed on the Recipes table. Is it possible to update the RecipeTags through table record in the same update call?

Problem coding a weak entity in sequelize

I am creating a cinema application. I have modeled the database on mySql but I am having trouble migrating it to Sequelize. I have followed the documentation but I am getting a lot of different errors.
I have tried using associations and indexes (as it should be). This is the model I am trying to make.
OCCUPIED_SEATS is composed of only two foreign keys and both make a unique index.
OCCUPIED_SEATS:
const SEATS = require("./Seats");
const SCREENING = require("./Screening");
const OCCUPIED_SEATS = sequelize.define("OCCUPIED_SEATS", {
//SEATS_ID
//SCREENING_ID
},
{
indexes: [
{
unique: true,
fields: [SEAT_ID, SCREENING_ID]
}
],
underscored: true
}
);
module.exports = OCCUPIED_SEATS;
SEATS:
const OCCUPIED_SEATS = require("./Occupied_Seats");
const SEATS = sequelize.define("SEATS", {
SEATS_ID: {
type: Sequelize.INTEGER,
primaryKey: true,
allowNull: false,
autoIncrement: true
},
ROW: {
type: Sequelize.STRING,
allowNull: false,
},
COLUMN: {
type: Sequelize.INTEGER,
allowNull: false
},
},
{
underscored: true
}
);
SEATS.hasMany(OCCUPIED_SEATS, {foreignKey: 'SEAT_ID'})
module.exports = SEATS;
SCREENING:
const OCCUPIED_SEATS = require("./Occupied_Seats");
const SCREENING = sequelize.define("SCREENING", {
SCREENING_ID: {
type: Sequelize.INTEGER,
primaryKey: true,
allowNull: false,
autoIncrement: true
},
SCREENING_START_TIME: {
type: Sequelize.TIME,
allowNull: false,
},
DATE: {
type: Sequelize.DATE,
allowNull: false
}
},
{
underscored: true,
indexes: [
{
unique: true,
fields: [ROOM_ID, SCREENING_START_TIME, DATE]
}
]
}
);
SCREENING.hasMany(OCCUPIED_SEATS, {foreignKey: 'SCREENING_ID'});
module.exports = SCREENING;
The error I am getting when I try this is:
[💻] Error: SEATS.hasMany called with something that's not a subclass of Sequelize.Model
How should I code the model?
Looks like in the new version of Sequelize you have to define your models through Sequelize.Model type:
class Seats extends Sequelize.Model {}
Seats.init({
id: {
type: Sequelize.INTEGER,
primaryKey: true,
allowNull: false,
autoIncrement: true
},
row: {
type: Sequelize.STRING,
allowNull: false,
},
...
});
module.exports = Seats;
And then somewhere else:
Seats.hasMany(OccupiedSeatc, {foreignKey: 'SEAT_ID'})
See model definition docs and accociation docs.

How to add foreign key using sequelize mysql

"I have 2 tables "Users" and "Profile_personals". How do I add a foreign key constraint to my profile personals using my "user_id" primary that's inside my Users table? I'm working with node.js, sequelize mysql.
Users(parent Table):
const Sequelize = require('sequelize')
const db = require("../database/db.js")
module.exports = db.sequelize.define(
"users",
{
user_id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
email: {
type: Sequelize.STRING
},
password: {
type: Sequelize.STRING
}
},
{
timestamps: false
}
)
Personals(Child Table):
const Sequelize = require('sequelize')
const db = require("../database/db.js")
module.exports = db.sequelize.define(
'profile_personals',
{
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
biography: {
type: Sequelize.STRING
}
},
{
timestamps: false
}
)
Do it this way, I hope it's what you're looking for.
module.exports = db.sequelize.define(
'profile_personals',
{
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
biography: {
type: Sequelize.STRING
},
// It is possible to create foreign keys:
user_id: {
type: Sequelize.INTEGER,
references: {
// This is a reference to another model
model: Users,
// This is the column name of the referenced model
key: 'user_id'
}
}
},
{
timestamps: false
}
);

sequelize - how to update an association in n-m relation including join table

I have two tables (user, tag) that are connected to each other with a belongsToMany relationship through a join entity (user_tag):
sequelize.define('tag', {
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true
},
type: {
type: DataTypes.STRING
}
}, {
classMethods: {
associate: function (models) {
this.belongsToMany(models.user, {as: "users", through: models.user_tag });
},
}
}
sequelize.define('user', {
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true
},
name: {
type: DataTypes.STRING,
},{
classMethods: {
associate: function (models) {
this.belongsToMany(models.tag, { as:"tags", through: models.user_tags });
}
}
}
sequelize.define('user_tag', {
type: DataTypes.STRING,
param1: DataTypes.INTEGER,
priority: DataTypes.INTEGER
}, {
freezeTableName: true,
paranoid: true
});
Now, a user can update all his tags, including all the specific information on the join entity (user_tag) for example priority and param1.
I'm aware of setAssociation [ e.g. user.setTag(myTags) ], however, how do I set the matching param1 and priority properties?
According to Sequelize's documentation when adding a new relationship with belongsToMany, you can pass in additional attributes to the option object and that data will get added to the through model.
user.setTag(myTags, { param1: 1, priority: 1 });

Set safe-deleting mode for relations table in Sequelize.js

So, assume we have that Sequelize model:
var User = sequelize.define("User", {
id: {
type: DataTypes.STRING(45),
allowNull: false,
primaryKey: true
},
password: {
type: DataTypes.STRING(60),
allowNull: false
},
email: {
type: DataTypes.STRING(45),
allowNull: false,
unique: true
},
firstName: {
type: DataTypes.STRING(45),
allowNull: true,
defaultValue: null
}
},
{
tableName: 'profiles',
classMethods: {
associate: function(models) {
User.belongsToMany(User, {through: 'friends', as:'friend'});
}
}
});
after calling associate() method, it will create an extra table friends with columns userId, friendId, createdAt and updatedAt. The case is I need to use this table with safe-deleting mode, in other words, I have to add 'deleted' column somehow. I tried to use paranoid: true in belongsToMany's attributes, didn't work. Is there any ways to do it?
Maybe you can create an model/table which name is Friend. And you can set paranoid: true in that model. And when you deleted an User, it keeps User's friend relation was keeping in that model.
I hope it works. :)