Sequalize relationship betwen same model - node.js

I am creating a chat application and trying to create a relationship between User and User through friendship. So far I can create a relationship, but in the end only one user assigned a friend. I'm using Express, sequalize with postgress deployed to heroku. I don't know how to achieve it, any help is appreciated
migration:
`enter code here`await queryInterface.createTable('users', { id: { type: DataTypes.UUID, primaryKey: true, defaultValue: DataTypes.UUIDV4, } }, }); await queryInterface.createTable('friendships', { id: { type: DataTypes.UUID, primaryKey: true, defaultValue: DataTypes.UUIDV4, }, user: { type: DataTypes.UUID, allowNull: false, references: { model: 'users', key: 'id' }, }, friend: { type: DataTypes.UUID, allowNull: false, references: { model: 'users', key: 'id' }, }, status: { type: DataTypes.ENUM('PENDING', 'ACCEPTED', 'DENIED'), allowNull: false, defaultValue: 'PENDING', }, });
friendship model:
Friendship.init(
{
id: {
type: DataTypes.UUID,
primaryKey: true,
defaultValue: DataTypes.UUIDV4,
},
user: {
type: DataTypes.UUID,
allowNull: false,
references: {
model: 'users',
key: 'id',
},
},
friend: {
type: DataTypes.UUID,
allowNull: false,
references: {
model: 'users',
key: 'id',
},
},
status: {
type: DataTypes.ENUM('PENDING', 'ACCEPTED', 'DENIED'),
allowNull: false,
defaultValue: 'PENDING',
},
},
{
sequelize,
underscored: true,
timestamps: false,
modelName: 'friendship',
}
);
associations:
User.belongsToMany(User, { as: 'friends', through: Friendship, foreignKey: 'user',
otherKey: 'friend' });
Friendship.belongsTo(User, { as: 'info', foreignKey: 'friend' });
controller:
export const addFriend = async (req: Request, res: Response) => {
try {
const { friendId } = req.body;
const userId = req.decodedToken?.id;
const friend = await User.findByPk(friendId, {
attributes: { exclude: ['passwordHash'] },
include: [{ model: User, as: 'friends' }],
});
if (friend)
await Friendship.create({
user: userId,
friend: friend.id,
status: 'PENDING',
});
return res.status(200).json({ status: 'success' });
} catch (e) {
res.status(500).json({ error: 'The server cannot create the user' });
console.log(e);
}
};
response:
"users": {
"count": 2,
"rows": [
{
"id": "e7c7ce39-953a-45e7-a892-a5f99554382e",
"email": "admin",
"username": "admin",
"name": null,
"surname": null,
"age": null,
"public": true,
"image": null,
"friends": [
{
"id": "13029ad9-7199-47d5-bd1c-7d939b26150e",
"email": "admin2",
"username": "admin",
"passwordHash": "$2b$10$GajlewYeiGvUOOV08YOzLuedV/8.KJNUeHB4WPKlUFxErj91ljfWq",
"name": null,
"surname": null,
"age": null,
"public": true,
"image": null,
"friendship": {
"id": "a78b9336-f5a6-4153-b3e1-e44dbe1cc7a6",
"user": "e7c7ce39-953a-45e7-a892-a5f99554382e",
"friend": "13029ad9-7199-47d5-bd1c-7d939b26150e",
"status": "PENDING"
}
}
]
},
{
"id": "13029ad9-7199-47d5-bd1c-7d939b26150e",
"email": "admin2",
"username": "admin",
"name": null,
"surname": null,
"age": null,
"public": true,
"image": null,
"friends": []
}
Edit:
I made something like this, it's not perfect, but it's good for me
User.belongsToMany(User, { as: 'friends', through: Friendship, foreignKey: 'user' });
User.belongsToMany(User, { as: 'friend', through: Friendship, foreignKey: 'friend' });

Please consider a many to many relationship.
An user can be a friend of many users.
Many users can be friends of one user.
You may found the how-to implement in the official doc: here.
Basically, use belongsToMany in both associations:
Implementation
The main way to do this in Sequelize is as follows:
const Movie = sequelize.define('Movie', { name: DataTypes.STRING });
const Actor = sequelize.define('Actor', { name: DataTypes.STRING });
Movie.belongsToMany(Actor, { through: 'ActorMovies' });
Actor.belongsToMany(Movie, { through: 'ActorMovies' });

Related

Count in Many-to-Many relationship

I want to count the number of likes when I fetch the post details.
User Model
User.init(
{
id: {
allowNull: false,
primaryKey: true,
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
},
userName: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
field: 'user_name',
},
}
);
static associate(models) {
// User has many posts --> One-to-Many Relationship
this.hasMany(models.Post, {
foreignKey: 'userId',
});
// Likes relationship
this.belongsToMany(models.Post, {
through: 'PostLikes',
foreignKey: 'userId',
as: 'likes',
});
}
And here is the Post Model
Post.init(
{
id: {
type: DataTypes.UUID,
primaryKey: true,
allowNull: false,
defaultValue: DataTypes.UUIDV4,
},
body: {
type: DataTypes.STRING,
allowNull: false,
},
}
);
static associate(models) {
// User-Post Relationship
this.belongsTo(models.User, {
foreignKey: 'userId',
});
// Likes Relationship
this.belongsToMany(models.User, {
through: 'PostLikes',
foreignKey: 'postId',
as: 'likes',
});
}
So, it now creates a joined table PostLikes and I am trying query that fetches the post along with the likes and number of likes on that post.
const postsIdCol = '"likes->PostLikes"."postId"';
const usersIdCol = '"likes->PostLikes"."userId"';
const postCol = '"Post"."id"';
const response = await Post.findOne({
where: {
id: postid,
},
// includeIgnoreAttributes : false,
attributes: [
'id', 'body', 'createdAt',
[sequelize.literal(`COUNT(${postsIdCol}) OVER (PARTITION BY ${postCol})`), 'likesCount'],
],
include: [
{
model: Comment, ----> Post is also associated with comments, ignore this
as: 'comments',
attributes: ['id', 'content', 'createdAt', 'updatedAt'],
},
{
model: User,
as: 'likes',
through: {
attributes: [],
},
attributes: ['id', 'userName'],
},
],
});
return response;
The Response I am getting on doing this query is like this :
{
"data": {
"id": "182d6377-5bf6-4b65-9e29-cb79acc85c0a",
"body": "hoping for the best",
"likesCount": "6", -----> this should be 3
"likes": [
{
"id": "1af4b9ea-7c58-486f-a37a-e46461487b06",
"userName": "sdfbsd",
},
{
"id": "484202b0-a6d9-416d-a8e2-6681deffa3d1",
"userName": "ndnadonfsu",
},
{
"id": "b3c70bee-e839-4449-b213-62813af031d1",
"userName": "difniandca",
}
]
}
}
You need another PARTITION BY column from the other association than the one that you want to count.
For example, if you want to count the likes, you need to partition by parent id (Post.id) and other association id (Comment.id).
If you want to count the comments, you need to partition by parent id (Post.id) and other association id ("likes->PostLikes"."UserId").
[Sequelize.literal(`COUNT(${postsIdCol}) OVER (PARTITION BY ${postCol}, "Comments"."id")`), 'likesCount']
Where it says "Comments", you need to add your comment table name.

Sequelize fetch include data based on alias where condition

I have two tables Employee and Department
Department
const Department = Sequelize.define(
"Department",
{
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true,
},
name: {
type: DataTypes.STRING,
allowNull: false,
},
},
{
underscored: true,
timestamps: true,
paranoid: true,
modelName: "Department",
tableName: "departments",
},
);
Department.associate = function (models) {
// associations can be defined here
models.Department.hasMany(models.Employee, {
foreignKey: "department_id",
as: "employees",
});
};
return Department;
};
Employee
const Employee = Sequelize.define(
"Employee",
{
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true,
},
name: {
type: DataTypes.STRING,
unique: true,
allowNull: false,
},
status: {
type: DataTypes.STRING,
defaultValue: "active",
},
departmentId: {
type: DataTypes.INTEGER,
},
},
{
underscored: true,
timestamps: true,
modelName: "Employee",
tableName: "employees",
},
);
Employee.associate = function (models) {
models.Employee.belongsTo(models.Department, {
foreignKey: "department_id",
as: "department",
});
};
return Employee;
};
Now I have to fetch the list of employees and putting a filter of department_id = 1
const { departmentId } = req.body;
const employees = await Employee.findAll({
include: [
{
model: Department,
where: {
id: departmentId,
},
},
],
});
I am getting the issue. Department is mapped by association "departments"
Cannot fetch the data.
I found the answer on sequelize docs
const employees = await Employee.findAll({
include: [
{
association: "department", // this is the place to change
where: {
id: departmentId,
},
},
],
});
Learnings:
We will not be able to put association and model together.
We will be able to use the Model if no association is there.
We will be able to use association if there is one.
References: https://sequelize.org/master/manual/eager-loading.html#:~:text=You%20can%20also%20include%20by%20alias%20name%20by%20specifying%20a%20string%20that%20matches%20the%20association%20alias

findAll sequelize with model returning odd values

Solved thanks to : https://stackoverflow.com/a/64702949/14585149
I am looking to list all transactions I have on a mysql database with the associated users.
I have 2 tables / models : Transaction & User
Transaction :
module.exports = function(sequelize, DataTypes) {
return sequelize.define('transactions', {
transaction_id: {
type: DataTypes.INTEGER(11),
allowNull: false,
primaryKey: true
},
user_id: {
type: DataTypes.INTEGER(11),
allowNull: false,
references: {
model: 'users',
key: 'user_id'
}
},
account_id: {
type: DataTypes.INTEGER(11),
allowNull: false,
references: {
model: 'accounts',
key: 'account_id'
}
},
}, { tableName: 'transactions' }); };
User :
module.exports = function(sequelize, DataTypes) {
return sequelize.define('users', {
user_id: {
type: DataTypes.INTEGER(11),
allowNull: false,
primaryKey: true,
references: {
model: 'recipients',
key: 'created_by'
}
},
contact_id: {
type: DataTypes.INTEGER(11),
allowNull: true,
references: {
model: 'contacts',
key: 'contact_id'
}
}, }, {
tableName: 'users',
timestamps: false
});
};
I have made the associations :
Transaction.hasOne(User, {foreignKey:'user_id'});
User.belongsTo(Transaction, {foreignKey:'user_id'});
and my code is :
api.get('/trx', async (req, res) => {
Transaction.findAll({
attributes: ['transaction_id','user_id','account_id'],
include: [{
model: User,
attributes: ['user_id']}]
})
.then(intrx => res.json(intrx))
.catch(res.catch_error)
});
the result :
[
{
"transaction_id": 1,
"user_id": 4,
"account_id": 1,
"user": {
"user_id": 1
}
},
{
"transaction_id": 2,
"user_id": 4,
"account_id": 75,
"user": {
"user_id": 2
}
}
]
why the values of user_id are different ?
I am expecting the user_id = 4 instead of 1 in my first result and user_id = 4 in my second result.
what I am doing wrong ?
You should reverse your associations like this:
Transaction.belongsTo(User, {foreignKey:'user_id'});
User.hasOne(Transaction, {foreignKey:'user_id'});
because Transaction has link to User i.e. belongs to it.

Why sequelize returns only one result?

i got some problems while writing code, here is some information:
Models:
'use strict';
module.exports = (sequelize, DataTypes) => {
const news = sequelize.define('news', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: DataTypes.INTEGER
},
title: DataTypes.STRING,
slug: {
type: DataTypes.STRING(64),
unique: true
},
body: DataTypes.STRING,
postedBy: DataTypes.INTEGER
}, {});
news.associate = function(models) {
models.news.hasMany(models.news_ratings, {
as: 'rate',
foreignKey: models.news_ratings.newsId
})
};
return news;
};
///////////////
'use strict';
module.exports = (sequelize, DataTypes) => {
const news_rating = sequelize.define('news_ratings', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: DataTypes.INTEGER
},
user: DataTypes.INTEGER,
rating: DataTypes.INTEGER,
newsId: DataTypes.INTEGER
}, {});
news_rating.associate = function(models) {
models.news_ratings.belongsTo(models.news, {
foreignKey: models.news.id
})
};
return news_rating;
};
Controller:
router.get('/news/:from/:count', (req, res, next) => {
if (Number.isInteger(Number(req.params.from)) && Number.isInteger(Number(req.params.count))) {
models.news.findAll({
offset: Number(req.params.from),
limit: Number(req.params.count),
include: [{
as: 'rate',
model: models.news_ratings,
attributes: [
[sequelize.fn('AVG', sequelize.col('rating')), 'rate']
]
}]
})
.then(response => {
console.log(response)
res.json(response)
})
.catch(err => {
console.error(err)
res.status(500).end()
})
} else next()
})
This code returns this result (then fetching /news/0/1):
[{
"id": 1,
"title": "First new",
"slug": "demo:first_new",
"body": "New 1. This is demo ^=^",
"postedBy": 0,
"createdAt": "2020-07-22T13:53:48.000Z",
"updatedAt": "2020-07-22T13:53:48.000Z",
"rate": [
{
"rate": "-0.3333"
}
]
}]
But I have 5 news in my database!
...And then I fetch /news/0/5, i got this:
[
{
"id": 1,
"title": "First new",
"slug": "demo:first_new",
"body": "New 1. This is demo ^=^",
"postedBy": 0,
"createdAt": "2020-07-22T13:53:48.000Z",
"updatedAt": "2020-07-22T13:53:48.000Z",
"rate": [
{
"rate": "0.0000"
}
]
}
]
Look, rate is invalid! It should be -0.3333!
Can someone explain me, why this happen and how to resolve this issue?

findAll doesn't get object structure according to Includes Sequelize

I have tables like Medics, MedicalSpecialties and Users. Models are define like:
Users Model
const Database = require('../sequelize');
const UserModel = Database
.getInstance()
.define('users', {
UserId: {
type: Database.FIELD_TYPE_ENUM.INTEGER,
primaryKey: true,
autoIncrement: true
},
FirstName: Database.FIELD_TYPE_ENUM.STRING,
MiddleName: Database.FIELD_TYPE_ENUM.STRING,
LastName: Database.FIELD_TYPE_ENUM.STRING,
SecondLastName: Database.FIELD_TYPE_ENUM.STRING,
ID: Database.FIELD_TYPE_ENUM.STRING,
Email: Database.FIELD_TYPE_ENUM.STRING,
Password: Database.FIELD_TYPE_ENUM.STRING,
CellPhoneNumber: Database.FIELD_TYPE_ENUM.STRING,
OtherPhoneNumber: Database.FIELD_TYPE_ENUM.STRING,
Deleted: Database.FIELD_TYPE_ENUM.BOOLEAN
});
module.exports = UserModel;
Medical Specialties Model
const Database = require('../sequelize');
const MedicalSpecialtyModel = Database
.getInstance()
.define('medicalspecialties', {
MedicalSpecialtyId: {
type: Database.FIELD_TYPE_ENUM.INTEGER,
primaryKey: true,
autoIncrement: true
},
Description: Database.FIELD_TYPE_ENUM.STRING,
CreatedUserId: {
type: Database.FIELD_TYPE_ENUM.INTEGER,
references: {
model: 'users',
key: 'UserId'
}
},
UpdatedUserId: {
type: Database.FIELD_TYPE_ENUM.INTEGER,
references: {
model: 'users',
key: 'UserId'
},
allowNull: true
},
createdAt: Database.FIELD_TYPE_ENUM.DATETIME,
updatedAt: Database.FIELD_TYPE_ENUM.DATETIME
});
module.exports = MedicalSpecialtyModel;
Medics Model
const Database = require('../sequelize');
const MedicModel = Database
.getInstance()
.define('medics', {
MedicId: {
type: Database.FIELD_TYPE_ENUM.INTEGER,
primaryKey: true,
autoIncrement: true
},
UserId: {
type: Database.FIELD_TYPE_ENUM.INTEGER,
primaryKey: true,
autoIncrement: false,
references: {
model: 'users',
key: 'UserId'
}
},
MedicalSpecialtyId: {
type: Database.FIELD_TYPE_ENUM.INTEGER,
references: {
model: 'medicalspecialties',
key: 'MedicalSpecialtyId'
}
},
Code: Database.FIELD_TYPE_ENUM.STRING,
CreatedUserId: {
type: Database.FIELD_TYPE_ENUM.INTEGER,
references: {
model: 'users',
key: 'UserId'
}
},
UpdatedUserId: {
type: Database.FIELD_TYPE_ENUM.INTEGER,
references: {
model: 'users',
key: 'UserId'
},
allowNull: true
}
});
module.exports = MedicModel;
What I want to do is to get results with object parent child Representation like
[
{
"MedicId": 1,
"Code": "test1",
"user": {
"UserId": 4,
"FirstName": "John",
"MiddleName": null,
"LastName": "Doe",
"SecondLastName": null,
},
"medicalspecialty": {
"MedicalSpecialtyId": 3,
"Description": "Doctor"
}
}
]
But instead I'm getting this result:
[
{
"MedicId": 1,
"Code": "test1",
"user.UserId": 4,
"user.FirstName": "John",
"user.MiddleName": null,
"user.LastName": "Doe",
"user.SecondLastName": null,
"medicalspecialty.MedicalSpecialtyId": 3,
"medicalspecialty.Description": "Doctor"
}
]
This is how I'm pulling data:
static getAllMedics() {
MedicModel.belongsTo(MedicalSpecialtyModel, {
foreignKey: 'MedicalSpecialtyId'
});
MedicModel.belongsTo(UserModel, {
foreignKey: 'UserId'
});
UserModel.belongsTo(MedicModel);
MedicalSpecialtyModel.hasMany(MedicModel);
const attributes = ['MedicId', 'Code'];
return MedicModel.findAll({
attributes,
include: [{
model: UserModel,
attributes: ['UserId', 'FirstName', 'MiddleName', 'LastName', 'SecondLastName'],
where: {
Deleted: false
},
required: true,
nested: true
}, {
model: MedicalSpecialtyModel,
attributes: ['MedicalSpecialtyId', 'Description'],
required: true,
nested: true
}],
raw: true
});
}
Hope you can help me.
The raw property on a find call flattens the structure.
Basically do a find without raw: true.
You could get more info about it here
At the end it was my error.
When initializing Sequelize I had added the option row: true.
new Sequelize(..., {
...,
row: true
})
My apologies.

Resources