I'm having problem with an additional attribute in the join table of the belongsToMany relation.
In the set or add method this attribute is not being passed to mysql.
I'm following the documentation pass as "through" the attribute within the set method, but it is not working.
Would anyone know what could be wrong since following the documentation is not working?
Note: The registration and update of the join is correct, only the additional attribute that is not being passed to the table.
Functionality Model:
export default function(sequelize, DataTypes) {
const Functionality = sequelize.define('functionality', {
id: {
type: DataTypes.INTEGER(11),
allowNull: false,
primaryKey: true,
autoIncrement: true
},
name: {
field: 'name',
type: DataTypes.STRING(300),
allowNull: false
}
}, {
classMethods: {
associate: function(models) {
Functionality.belongsToMany(models.privilege, { as: 'privilegies', through: models.functionality_privilege, foreignKey: 'functionality_id' });
}
},
tableName: 'functionality',
freezeTableName: true,
timestamps: true,
createdAt: 'createdAt',
updatedAt: 'updatedAt'
});
return Functionality;
}
Privilege Model:
export default function(sequelize, DataTypes) {
const Privilege = sequelize.define('privilege', {
id: {
type: DataTypes.INTEGER(11),
allowNull: false,
primaryKey: true,
autoIncrement: true
},
name: {
field: 'name',
type: DataTypes.STRING(300),
allowNull: false
}
}, {
classMethods: {
associate: function(models) {
Privilege.belongsToMany(models.functionality, { as: 'functionalities', through: models.functionality_privilege, foreignKey: 'privilege_id' });
}
},
tableName: 'privilege',
freezeTableName: true,
timestamps: true,
createdAt: 'createdAt',
updatedAt: 'updatedAt'
});
return Privilege;
}
FunctionalityPrivilege Model:
export default function(sequelize, DataTypes) {
const Functionalityprivilege = sequelize.define('functionality_privilege', {
id: {
type: DataTypes.INTEGER(11),
allowNull: false,
primaryKey: true,
autoIncrement: true
},
edit: {
field: 'edit',
type: DataTypes.BOOLEAN
}
}, {
tableName: 'functionality_privilege',
freezeTableName: true,
timestamps: true,
createdAt: 'created_at',
updatedAt: 'updated_at'
});
return Functionalityprivilege;
}
Method Create:
create(options) {
let obj = options.payload;
return this.functionalityDao.create(obj)
.then((result) => {
return result.setPrivilegies(obj.privilegies, { through: { edit: obj.permissions }})
});
}
OR
return result.setPrivilegies(obj.privilegies, { through: { edit: true }})
I didn't manage to do this with 'set' function but it worked for me with 'add' method:
result.addPrivilege(privilege, { through: { edit: true }});
It should work for the already existing privilege. It didn't work with the array of entities (privileges in your case), so I had to call 'add' method several times. Like this:
return Promise.all(
privileges.map(privilege => result.addPrivilege(privilege, { through: { edit: true }}));
)
Related
I'm trying to run the following code block, for some reason the query tries to insert it into a column labeled "users->user_group"."userUuid", despite the fact that I have not reference the string literal userUuid once in the project (through search not in the code base), also check columns in pg-admin (using PostgreSQL), both columns in the user_group table are user_uuid and group_uuid, both columns are also validated and populated properly.
const result = await group.findAll({
include: user,
});
Postman body returns the following error
"hint": "Perhaps you meant to reference the column "users->user_group.user_uuid".",
I have 3 models user, group and user_group. The relations have been defined per documentation and countless other articles and videos.
user model
module.exports = (sequelize, DataTypes) => {
const user = sequelize.define(
"user",
{
uuid: {
type: DataTypes.STRING,
primaryKey: true,
allowNull: false,
unique: true,
},
username: {
type: DataTypes.STRING,
unique: true,
allowNull: false,
},
{
freezeTableName: true,
}
);
user.associate = (models) => {
user.belongsToMany(models.group, {
// as: "userUuid",
through: models.user_group,
foreignKey: "user_uuid",
});
};
return user;
};
group model
module.exports = (sequelize, DataTypes) => {
const group = sequelize.define(
"group",
{
uuid: {
type: DataTypes.STRING,
primaryKey: true,
allowNull: false,
unique: true,
},
title: {
type: DataTypes.STRING,
unique: true,
allowNull: false,
},
},
{
freezeTableName: true,
}
);
group.associate = (models) => {
group.belongsToMany(models.user, {
// as: "groupUuid",
through: models.user_group,
foreignKey: "group_uuid",
});
};
return group;
};
user_group model
module.exports = (sequelize, DataTypes) => {
const user_group = sequelize.define(
"user_group",
{
uuid: {
type: DataTypes.STRING,
primaryKey: true,
allowNull: false,
unique: true,
},
user_uuid: {
type: DataTypes.STRING,
allowNull: false,
references: {
model: "user",
key: "uuid",
},
},
group_uuid: {
type: DataTypes.STRING,
allowNull: false,
references: {
model: "group",
key: "uuid",
},
},
author: {
type: DataTypes.STRING,
unique: true,
allowNull: true,
},
},
{
freezeTableName: true,
}
);
user_group.associate = (models) => {
user_group.belongsTo(models.user, {
foreignKey: "user_uuid",
});
user_group.belongsTo(models.group, {
foreignKey: "group_uuid",
});
};
return user_group;
};
Any help is much apprecaited, thanks!
You should indicate otherKey option along with foreignKey in belongsToMany in order to indicate a foreign key column on the other model otherwise you will end up with a default name of an other key, see below:
The name of the foreign key in the join table (representing the target model) or an object representing the type definition for the other column (see Sequelize.define for syntax). When using an object, you can add a name property to set the name of the column. Defaults to the name of target + primary key of target (your case: user+uuid)
group.belongsToMany(models.user, {
// as: "groupUuid",
through: models.user_group,
foreignKey: "group_uuid",
otherKey: "user_uuid"
});
const result = await group.findAll({
include: {user},
});
you should to create like this. baecause you missing this {}.
PROBLEM RESUME:
I'm having trouble when I try to do a findOne or findAll.
At the findOne or findAll answer I catch all the informations from the user but in the answer there aren't any data of "t_roles" associated to this user.
But the stranger issue is that if I use raw: true inside the findOne for example, the informations of roles are shown.
I Have two models
User:
const dbUser = {
a_id: {
primaryKey: true,
autoIncrement: true,
type: Sequelize.BIGINT,
},
a_date_created: {
type: Sequelize.DATE,
allowNull: false,
},
a_first_name: {
type: Sequelize.STRING,
allowNull: false,
},
a_last_name: {
type: Sequelize.STRING,
allowNull: false,
},
a_email: {
type: Sequelize.TEXT,
unique: true,
allowNull: false,
},
a_password: {
type: Sequelize.STRING,
allowNull: false,
},
a_birthday: {
type: Sequelize.DATE,
allowNull: false,
},
a_is_active: {
type: Sequelize.BOOLEAN,
allowNull: false,
},
};
User.init(dbUser, {
sequelize: db,
modelName: 't_user',
timestamps: false,
tableName: 't_users',
});
User.associate = (models) => {
console.log('ASSOCIADO')
User.belongsToMany(models.Role, {
through: { model: UserRole, unique: false },
as: 'roles',
foreignKey: 'a_user',
otherKey: 'a_role',
});
};
and Role:
const dbRole = {
a_id: {
primaryKey: true,
autoIncrement: true,
type: Sequelize.BIGINT,
},
a_role: {
type: Sequelize.STRING,
allowNull: false,
},
};
Role.init(dbRole, {
sequelize: db,
modelName: 't_role',
timestamps: false,
tableName: 't_roles',
});
Role.associate = (models) => {
Role.belongsToMany(models.User, {
through: { model: UserRole, unique: false },
as: 'UserOfRoles',
foreignKey: 'a_role',
otherKey: 'a_user',
});
};
As you can see I'm associating them using another model, UserRole:
const dbUserRole = {
a_id: {
primaryKey: true,
autoIncrement: true,
type: Sequelize.BIGINT,
},
a_role: {
type: Sequelize.INTEGER,
allowNull: false,
primaryKey: false,
references: {
model: Role,
key: 'a_id',
},
onDelete: 'CASCADE',
},
a_user: {
type: Sequelize.INTEGER,
allowNull: false,
references: {
model: User,
key: 'a_id',
},
onDelete: 'CASCADE',
},
};
UserRole.init(dbUserRole, {
sequelize: db,
modelName: 't_user_role',
timestamps: false,
tableName: 't_user_role',
});
UserRole.associate = (models) => {
UserRole.belongsTo(models.User, { targetKey: 'a_id', foreignKey: 'a_user' });
UserRole.belongsTo(models.Role, { targetKey: 'a_id', foreignKey: 'a_role' });
};
To create a user with a role (admin) I do like the code below:
onst createAdmin = async (body) => {
try {
const userResult = await createUser(body);
if (userResult.error) {
return {
ok: false,
error: userResult.error,
};
}
const isAdmin = await UserRole.create({
a_role: 1,
a_user: userResult.a_user_id,
});
return {
ok: true,
};
} catch (error) {
return {
ok: false,
error,
};
}
Seems to be working fine, because the user are being created, and the association using the "t_user_role" too, because the data is also being created at the table.
As I sad at the problem resume, my trouble is when I'm trying to do a findOne or findAll.
For example, when I try the code below, I catch all the informations from the user but in the answer there aren't any data of "t_roles" associated to this user.
const { body } = req;
try {
const result = await User.findOne({
where: {
a_id: 1,
},
include: [
{
association: 'roles',
attributes: ['a_role'],
through: {
attributes: [],
},
},
],
});
console.log('====================================');
console.log(JSON.stringify(result, null, 2));
console.log('====================================');
} catch (error) {
console.error(error);
}
If I use raw: true inside the findOne for example, the informations of roles are shown, so I presume that the association is correct.
I really appreciate any help to find what I'm missing here.
Thanks
Well, after days working on and trying different ways to solve this problem, a friend of mine just helped me starting again the entire project, following the documentation of Sequelize and the exact structure we did before, but a little bit more simple, and surprisingly ... worked. So I suppose that was something with migrations ore models or whatever, but we can't really say.
I'm having trouble getting Sequelize.js to soft delete the rows in my table. I used Sequelize cli to do all my migrations and I'm not using the sync feature to resync the database on start. I have the timestamp fields and even the deletedAt field in my migration and models (model has paranoid: true also) and no matter what it still deletes the row instead of adding a timestamp to the deletedAt field. I noticed when do any querying it doesn't add the deletedAt = NULL in the query like I've seen in some tutorials. I'm using Sequelize.js v3.29.0.
Model File:
'use strict';
module.exports = function(sequelize, DataTypes) {
var Collection = sequelize.define('Collection', {
userId: {
type: DataTypes.INTEGER,
allowNull: false,
validate: {
isInt: true
}
},
name: {
type: DataTypes.STRING,
allowNull: false
},
description: DataTypes.TEXT,
createdAt: {
allowNull: false,
type: DataTypes.DATE
},
updatedAt: {
allowNull: false,
type: DataTypes.DATE
},
deletedAt: {
type: DataTypes.DATE
}
}, {
classMethods: {
associate: function(models) {
Collection.belongsTo(models.User, { foreignKey: 'userId' })
}
}
}, {
timestamps: true,
paranoid: true
});
return Collection;
};
Migration File:
'use strict';
module.exports = {
up: function(queryInterface, Sequelize) {
return queryInterface.createTable('Collections', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
userId: {
allowNull: false,
type: Sequelize.INTEGER
},
name: {
allowNull: false,
type: Sequelize.STRING
},
description: {
type: Sequelize.TEXT
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
},
deletedAt: {
type: Sequelize.DATE
}
});
},
down: function(queryInterface, Sequelize) {
return queryInterface.dropTable('Collections');
}
};
Here is the code in the controller I'm using to destroy the collection object.
Collection.findOne({
where: {
id: collectionId,
userId: user.id
}
}).then(function(collection){
if (collection !== null) {
collection.destroy().then(function(){
res.redirect('/collection');
}).catch(function(error){
res.redirect('/collection/'+collectionId);
});
}
});
Make sure paranoid is attribute defined inside second object param.
..., {
classMethods: {
associate: function(models) {
Collection.belongsTo(models.User,{ foreignKey: 'userId' })
}
},
timestamps: true,
paranoid: true
}
You've defined paranoid as 3. Param and that is the problem.
I made some associate but it did not work, probably with me that something is wrong, ask for help.
There are two models
module.exports = function (sequelize, DataTypes) {
var pages_lang = require('./pages_lang')(sequelize, DataTypes);
return sequelize.define('pages', {
id: {
type: DataTypes.INTEGER(10),
allowNull: false,
primaryKey: true,
autoIncrement: true,
references : { model: "pages_lang", key: "page_id" }
},
name: {
type: DataTypes.STRING,
allowNull: false
},
published: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: '0'
},
createdAt: {
type: DataTypes.DATE,
allowNull: false,
defaultValue: '0000-00-00 00:00:00'
},
updatedAt: {
type: DataTypes.DATE,
allowNull: false,
defaultValue: '0000-00-00 00:00:00'
}
}, {
classMethods: {
associate: function (models) {
this.hasMany(models.pages_lang, {onDelete: 'SET NULL', onUpdate: 'CASCADE', foreignKey: 'page_id', as: 'pages', through: models.pages_lang});
},
getAll() {
return this.findAll({include: [{model: pages_lang, as: 'pages_lang'}]}).then(function (result) {
return result;
});
}
}
});
};
module.exports = function (sequelize, DataTypes) {
return sequelize.define('pages_lang', {
id: {
type: DataTypes.INTEGER(10),
allowNull: false,
primaryKey: true,
autoIncrement: true
},
page_id: {
type: DataTypes.INTEGER(10),
allowNull: false,
references : { model: "pages", key: "id" }
},
content: {
type: DataTypes.TEXT,
allowNull: false
}
}, {
classMethods: {
associate: function (models) {
this.belongsTo(models.pages, {foreignKey: 'id', foreignKeyConstraint:true, as: 'pages', through: models.pages});
}
}
});
};
But when you call results in an error
Unhandled rejection Error: pages_lang (pages_lang) is not associated
to pages!
Advance very grateful for the help
Your association alias (as) should match what you pass to findAll
this.hasMany(models.pages_lang, {onDelete: 'SET NULL', onUpdate: 'CASCADE', foreignKey: 'page_id', as: 'pages_lang' });
return this.findAll({include: [{model: pages_lang, as: 'pages_lang'}]});
Since the model is already called pages_lang, you can also skip the alias completely:
this.hasMany(models.pages_lang, {onDelete: 'SET NULL', onUpdate: 'CASCADE', foreignKey: 'page_id'});
return this.findAll({include: [pages_lang]});
Notice that I removed the through argument - it should only be used for belongsToMany (many-to-many)
I've been through several questions on the site but I still can't see what I'm doing wrong here, so any help would be greatly appreciated.
I'm getting the error:
Organization (organizations) is not associated to User!
Org Model:
module.exports = function (sequelize, DataTypes) {
return sequelize.define('Organization', {
organizationID: {
primaryKey: true,
type: DataTypes.INTEGER(11),
allowNull: false,
},
name: {
type: DataTypes.STRING,
allowNull: false,
},
description: {
type: DataTypes.STRING,
allowNull: true,
}
},
{
tableName: "spa_vOrganization",
freezeTableName: true,
classMethods: {
associate: function (models) {
Organization.hasMany(models.User, {
as: 'users',
through: models.User_Tenant_Organization,
foreignKey: 'organizationID'
});
}
},
});
};
User Model:
module.exports = function (sequelize, DataTypes) {
return sequelize.define('User', {
userID: {
primaryKey: true,
type: DataTypes.INTEGER(11),
allowNull: false,
},
password: {
type: DataTypes.STRING,
allowNull: false,
},
email: {
type: DataTypes.STRING,
allowNull: false,
}
},
{
tableName: "spa_User",
freezeTableName: true,
classMethods: {
associate: function(models) {
User.hasMany(models.Organization, { as: "organizations", through: models.User_Tenant_Organization, foreignKey: 'userID'});
}
}
}
);
};
Matrix table model:
module.exports = function (sequelize, DataTypes) {
return sequelize.define('User_Tenant_Organization', {
userTenantOrganizationID: {
primaryKey: true,
type: DataTypes.INTEGER(11),
allowNull: false,
},
userID: {
type: DataTypes.INTEGER(11),
allowNull: false,
},
organizationID: {
type: DataTypes.INTEGER(11),
allowNull: false,
},
tenantID: {
type: DataTypes.INTEGER(11),
allowNull: false,
},
},
{
tableName: "spa_User_Tenant_Organization",
freezeTableName: true,
});
};
What I'm trying to do is just pull back a user with their organizations eagerly loaded. Here's what I'm using:
models.User.findOne({where: {
email: body.email
}, include: [ {model:models.Organization, as: 'organizations'}]}).complete( function (err, user) {
// do something with the user
}
I've tried with and without foreignKey definitions on both User and Organization, nothing makes any difference. I'm obviously misunderstanding something about the associations. Can anyone tell me where I'm going wrong please?
I found the problem. The associations in the above code are actually correct - what was failing was my models/index.js, which had been automatically generated by the yeoman generator-angular-express-sequelize
index.js was looping through the model files, importing them into the sequelize object and storing a copy in an array db[], then trying to run the classMethod associate(), but it was calling models.options.associate() instead of models.associate():
Object.keys(db).forEach(function (modelName) {
if (db[modelName].options.hasOwnProperty('associate')) {
db[modelName].options.associate(db);
}
});
I've fixed that by removing the ".options" and everything works fine.
Pull request to fix the problem is here for reference: https://github.com/rayokota/generator-angular-express-sequelize/pull/7