Checking if two values match from one to another table - javascript

So I started doing a app with JavaScript ORM- Sequelize.
I have a table called Workouts.js where the exercises are the id's in a table called Exercises.js.
Workouts.js
id
exercise_one
exercise_two
exercise_three
date
1
1
2
4
2022-02-21
2
4
3
2
2022-02-23
3
3
1
1
2022-02-25
I have another table called Workout_Volume.js which has the following values:
Workout_Volume.js
id
workout_id
exercise_id
sets
reps
weight
1
1
1
3
10
60
2
1
4
4
12
40
3
3
3
3
15
30
4
2
4
5
5
80
So my question is what is the correct way to validate in Workout_Volume.js workouit_id and exercise_id match as in Workouts.js when creating and updating Workout_Volume.js?
Workouts.js
const workout = (sequelize, DataTypes) => {
const Workout = sequelize.define(
'workouts', {
exercise_one: {
type: DataTypes.INTEGER(), allowNull: false,
references: { model: "exercises", key: "id" },
validate: {
notNull: { msg: "You need to provide exercise_id !" }
}
},
exercise_two: {
type: DataTypes.INTEGER(), allowNull: true,
references: { model: "exercises", key: "id" },
},
exercise_three: {
type: DataTypes.INTEGER(), allowNull: true,
references: { model: "exercises", key: "id" },
},
exercise_four: {
type: DataTypes.INTEGER(), allowNull: true,
references: { model: "exercises", key: "id" },
},
exercise_five: {
type: DataTypes.INTEGER(), allowNull: true,
references: { model: "exercises", key: "id" },
},
exercise_six: {
type: DataTypes.INTEGER(), allowNull: true,
references: { model: "exercises", key: "id" },
},
exercise_seven: {
type: DataTypes.INTEGER(), allowNull: true,
references: { model: "exercises", key: "id" },
},
exercise_eight: {
type: DataTypes.INTEGER(), allowNull: true,
references: { model: "exercises", key: "id" },
},
date: {
type: DataTypes.DATEONLY, allowNull: false,
validate: {
notNull: { msg: "You need to provide date !" }
}
}
},
{
timestamps: false,
freezeTableName: true,
})
Workout.associate = models => {
Workout.belongsToMany(models.exercises, {
foreignKey: "exercise_one",
through: 'exerciseOne',
targetKey: "id"
})
Workout.belongsToMany(models.exercises, {
foreignKey: "exercise_two",
through: 'exercisTwo',
targetKey: "id"
})
Workout.belongsToMany(models.exercises, {
foreignKey: "exercise_three",
through: 'exerciseThree',
targetKey: "id"
})
Workout.belongsToMany(models.exercises, {
foreignKey: "exercise_four",
through: 'exerciseFour',
targetKey: "id"
})
Workout.belongsToMany(models.exercises, {
foreignKey: "exercise_five",
through: 'exerciseFive',
targetKey: "id"
})
Workout.belongsToMany(models.exercises, {
foreignKey: "exercise_six",
through: 'exerciseSix',
targetKey: "id"
})
Workout.belongsToMany(models.exercises, {
foreignKey: "exercise_seven",
through: 'exerciseSeven',
targetKey: "id"
})
Workout.belongsToMany(models.exercises, {
foreignKey: "exercise_eight",
through: 'exerciseEight',
targetKey: "id"
})
Workout.belongsTo(models.workout_volume, {
foreignKey:"id",
targetKey: "workout_id",
through: "workout_volume"
})
}
Workout.sync()
return Workout
}
module.exports = workout
Workout_Volume.js
const workoutVolume = (sequelize, DataTypes) => {
const Workout_Volume = sequelize.define(
'workout_volume', {
workout_id: {
type: DataTypes.INTEGER, allowNull: false,
references: { model: "workouts", key: "id" },
validate: {
notNull: { msg: "You need to provide workout_id !" }
}
},
exercise_id: {
type: DataTypes.INTEGER, allowNull: false,
validate: {
notNull: { msg: "You need to provide exercise_id !" }
},
},
sets: {
type: DataTypes.INTEGER, allowNull: false,
validate: {
min: 1,
max: 100,
notNull: { msg: "You need to provide sets!" }
}
},
reps: {
type: DataTypes.INTEGER, allowNull: false,
validate: {
min: 1,
max: 100,
notNull: { msg: "You need to provide reps!" }
}
},
weight: {
type: DataTypes.INTEGER, allowNull: false,
validate: {
min: 0,
max: 1000,
notNull: { msg: "You need to provide sets!" }
}
}
},
{
timestamps: false,
freezeTableName: true,
},
)
Workout_Volume.associate = models => {
Workout_Volume.belongsTo(models.workouts,{
foreignKey: "workout_Id",
as: "workoutId",
targetKey: "id"
})
}
Workout_Volume.sync()
return Workout_Volume
}
module.exports = workoutVolume
My thoughts on making is:
To make associations with exercise_id to each exercise value in Workouts.js. The problem is that the exercises are 8 and I think the project will become more hard-coded;
Don't make assosiactions but make a for loop where I will check if the requested workout_id and exercises_id match the Workout.js values;
Or if there is better way to consturct the tables so it makes more sence
Or if there is better way to construct tables or something else.
workoutVolume.controller.js
const models = require('../models');
const Workout_Volume = models.workout_volume;
exports.getAllWorkouts_Volume = async (req, res) => {
try {
const workout_volume = await Workout_Volume.findAll()
return res.status(200).send(workout_volume)
} catch (error) {
return res.status(500).send(error)
}
}
exports.getWorkout_Volume = async (req, res) => {
try {
const workout_volume = await Workout_Volume.findByPk(req.params.id)
res.status(200).send(workout_volume)
} catch (error) {
return res.status(500).send(error)
}
}
exports.createWorkout_Volume = async (req, res) => {
try {
const exerciseExists = await Workout_Volume.findAll({
where: {
exercise_id: req.body.exercise_id,
workout_id: req.body.workout_id
},
attributes: ["exercise_id", "workout_id"]
})
if (exerciseExists.length !== 0) {
return res.status(500).send("Exercise already done for this workout!")
}
await Workout_Volume.create(req.body)
return res.status(201).send(req.body)
} catch (error) {
return res.status(500).send(error)
}
}
exports.updateWorkout_volume = async (req, res) => {
try {
const workout_volume = await Workout_Volume.findByPk(req.params.id)
console.log(req.body)
const exerciseExists = await Workout_Volume.findAll({
where: {
exercise_id: req.body.exercise_id,
workout_id: req.body.workout_id
},
attributes: ["exercise_id", "workout_id"]
})
if (exerciseExists.length !== 0) {
return res.status(500).send("Exercise already done for this workout!")
}
await workout_volume.update(req.body)
return res.status(200).send(req.body)
} catch (error) {
return res.status(500).send(error)
}
}
The problem here is that when I create I can't create invalid workout_id but can create exercise_id which is not in Workout.js.
Also when I try to update it already the length is !== 0

You definitely need to create a table/model Workout_Excercise instead of adding columns in Workout table/model. That way you will have as many exercises in a certain workout as you want.
And the second great benefit of having Workout_Excercise is that you will be able to create a correct foreign key from Workout_Volume to Workout_Excercise:
Workout.hasMany(models.workoutExercises, {
foreignKey: "workoutId",
})
WorkoutExercise.belongsTo(models.exercises, {
foreignKey: "exerciseId",
})
WorkoutExercise.hasMany(models.workout_volume, {
foreignKey: "workoutExerciseId",
})
WorkoutVolume.belongsTo(models.workout_exercise, {
foreignKey: "workoutExerciseId",
})

Related

How to find several fields of a foreign key in a join table in Node.js Sequelize

I have a Node.js application with Express, Sequelize as ORM and PostgreSQL for the database. In this app I have candidate model and mission model as below.
'use strict';
const {
Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class candidat extends Model {
static associate(models) {
this.belongsToMany(models.mission, {
through: "candidat_mission",
foreignKey: "candidatId",
otherKey: "idMission",
});
}
}
candidat.init({
candidatId: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: DataTypes.INTEGER
},
lastName: {
type: DataTypes.STRING,
allowNull: false,
},
firstName: {
type: DataTypes.STRING,
allowNull: false,
},
email: {
isEmail: true,
allowNull: false,
type: DataTypes.STRING,
unique: true,
},
}, {
sequelize,
modelName: 'candidat',
tableName: 'candidat',
freezeTableName: true,
});
return candidat;
};
'use strict';
const {
Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class mission extends Model {
static associate(models) {
this.belongsToMany(models.candidat, {
through: "candidat_mission",
foreignKey: "idMission",
otherKey: "candidatId",
})
}
}
mission.init({
idMission: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: DataTypes.INTEGER
},
title: {
type: DataTypes.STRING,
allowNull: false
},
aliasTitle: {
type: DataTypes.STRING,
allowNull: true
},
description: {
type: DataTypes.TEXT,
allowNull: true
}
}, {
sequelize,
modelName: 'mission',
tableName: 'mission',
freezeTableName: true,
});
return mission;
};
These two models are linked in many-to-many by a candidate_mission join table. In this model, I added fields like a foreign key which points to another table, that of users.
'use strict';
const {
Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class candidat_mission extends Model {
static associate(models) {
this.belongsTo(models.user, { foreignKey: "fk_user" });
}
}
candidat_mission.init({
candidatMissionId: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: DataTypes.INTEGER
},
candidatId: {
type: DataTypes.INTEGER,
allowNull: false,
references: {
model: { tableName: 'candidat' },
key: "candidatId",
},
},
idMission: {
type: DataTypes.INTEGER,
allowNull: false,
references: {
model: { tableName: 'mission' },
key: "idMission",
},
},
fk_user: {
type: DataTypes.INTEGER,
allowNull: true,
references: {
model: { tableName: 'user' },
key: "userId",
},
},
}, {
sequelize,
modelName: 'candidat_mission',
tableName: 'candidat_mission',
timestamps: true,
freezeTableName: true,
});
return candidat_mission;
};
When I make a "GET" request, I do have the information from the candidate_mission table (if a candidate is linked to this mission), but for the user it only returns the ID and I would like it to return all the fields present in the Users model, what can I do?
Here, my function in the mission controller which allows to add a candidate to this mission :
const addCandidats = async (req, res) => {
try {
const mission = await Mission.findByPk(req.body.idMission);
if (mission) {
const candidat = await Candidat.findByPk(req.body.candidatId);
if (candidat) {
mission.addCandidat(candidat,
{through: {
fk_user: req.body.fk_user && req.body.fk_user
}});
return res.status(200).send(mission);
} else {
console.log("Candidat non trouvé");
return null;
}
} else {
console.log("Mission non trouvée!")
return null;
}
} catch (error) {
console.log(error);
}
};
Currently, my query returns me this :
"candidat_mission":
{
"candidatMissionId": 2,
"candidatId": 1,
"idMission": 7,
"fk_user": 1,
"createdAt": "2023-02-14T10:34:08.302Z",
"updatedAt": "2023-02-14T15:06:10.232Z"
},
And i want it to come back to me :
"candidat_mission":
{
"candidatMissionId": 2,
"candidatId": 1,
"idMission": 7,
"fk_user": {
"userId": 1,
"email": "blabla#gmail.com",
"name": "blabla"
},
"createdAt": "2023-02-14T10:34:08.302Z",
"updatedAt": "2023-02-14T15:06:10.232Z"
},
After associating 2 models, we have to query again to get the object along with the relationship.
await mission.addCandidat(candidat,
{through: {
fk_user: req.body.fk_user && req.body.fk_user
}});
const result = await CandidatMission.findOne({
where: { candidatId: req.body.candidatId, idMission: req.body.idMission },
include: models.user,
})
return res.status(200).send(result);

Empty Array when use random with Sequelize

I'm working on an API in Node.js with the Sequelize ORM.
I make an API route to retrieve a random question, it works one time out of three but often returns an empty array. I can't find a solution in the documentation to prevent this...
app.get('/:certifName/:levelName/random', async function (req, res) {
return await Certification.findOne(
{
attributes: ['id', 'label'],
include: [{
model: CertificationLevel,
as: "tcl",
required: true,
attributes: ['id', 'label', 'question_number', 'exam_duration'],
include: [{
attributes: ['id', 'label'],
model: CertificationChapter,
as: "tcc",
required: true,
limit: 1,
order: [ [ Sequelize.fn('RANDOM') ] ],
include: [{
model: Question,
as: "tq",
required: true,
include: [{
model: QuestionChoice,
as: "tqc",
required: false,
attributes: ['id', 'label_fr', 'is_answer'],
}],
}],
}],
where: { label: req.params.levelName }
}],
where: { label: req.params.certifName }
})
.then(data => {
if (data) {
res.send(data);
}
else
res.sendStatus(204);
})
.catch(err => {
res.status(500).send({
message:
err.message || "Error retrieving certification details"
});
});
});
The last model :
module.exports =
class CertificationLevel extends Sequelize.Model {
static init(sequelize) {
return super.init(
{
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
primaryKey: true
},
label: Sequelize.STRING,
slug: Sequelize.STRING,
description: Sequelize.TEXT,
question_number: Sequelize.INTEGER,
exam_duration: Sequelize.INTEGER,
created_at: {
type: Sequelize.DATE,
defaultValue: Sequelize.NOW
},
updated_at: Sequelize.DATE,
deleted_at: Sequelize.DATE
},
{
tableName: 't_certifications_levels',
sequelize,
underscored: true,
timestamps: false
},
);
}
static associate(models) {
this.belongsTo(models.Certification, {
onDelete: "CASCADE",
foreignKey: {
allowNull: false,
name: "certification_id"
}
}),
this.hasMany(models.CertificationChapter, { as:'tcc', foreignKey: 'level_id' })
this.hasMany(models.Subscription, { as:'ts',foreignKey: 'level_id' })
}
}
And this is a SQL query generate :
SELECT "Certification".*,
"tcl"."id" AS "tcl.id",
"tcl"."label" AS "tcl.label",
"tcl"."question_number" AS "tcl.question_number",
"tcl"."exam_duration" AS "tcl.exam_duration"
FROM
(SELECT "Certification"."id",
"Certification"."label"
FROM "t_certifications" AS "Certification"
WHERE "Certification"."label" = 'ISTQB'
AND
(SELECT "tcl"."certification_id"
FROM "t_certifications_levels" AS "tcl"
WHERE ("tcl"."label" = 'Fondation'
AND "tcl"."certification_id" = "Certification"."id")
LIMIT 1) IS NOT NULL
LIMIT 1) AS "Certification"
INNER JOIN "t_certifications_levels" AS "tcl" ON "Certification"."id" = "tcl"."certification_id"
AND "tcl"."label" = 'Fondation';
I don't know why I have two executing to my route?
I am a real beginner in back development...
Thank for you help

Sequelize many-to-many relation and one-to-many in intermediate table

Hi have a table Users with many to many relation to Groups through UsersGroups. UsersGroups has a FK to UsersGroupsRoles:
Users:
module.exports = (sequelize, Sequelize) => {
const Users = sequelize.define(
'Users',
{
id: {
type: Sequelize.UUID,
defaultValue: Sequelize.UUIDV4,
primaryKey: true,
},
name: {
type: Sequelize.STRING,
},
},
{}
);
Users.associate = function(models) {
Users.belongsToMany(models.Groups, { through: models.UsersGroups });
};
return Users;
};
Groups:
module.exports = (sequelize, Sequelize) => {
const Groups = sequelize.define(
'Groups',
{
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
primaryKey: true,
allowNull: false,
},
name: {
type: Sequelize.STRING,
},
},
{}
);
Groups.associate = function(models) {
Groups.belongsToMany(models.Users, { through: models.UsersGroups });
};
return Groups;
};
UsersGroups:
module.exports = (sequelize, Sequelize) => {
const UsersGroups = sequelize.define(
'UsersGroups',
{
order: {
allowNull: true,
type: Sequelize.INTEGER,
defaultValue: 10000,
},
},
{}
);
UsersGroups.associate = function(models) {
UsersGroups.belongsTo(models.UsersGroupsRoles, { as: 'UsersGroupsRoles', onDelete: 'CASCADE' });
};
return UsersGroups;
};
UsersGroupsRoles:
module.exports = (sequelize, Sequelize) => {
const UsersGroupsRoles = sequelize.define(
'UsersGroupsRoles',
{
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
primaryKey: true,
allowNull: false,
},
role: {
type: Sequelize.STRING,
},
},
{}
);
UsersGroupsRoles.associate = function(models) {
UsersGroupsRoles.hasMany(models.UsersGroups, { as: 'UsersGroupsRoles', onDelete: 'CASCADE' });
};
return UsersGroupsRoles;
};
Now I want to query Users and UsersGroups, and get the UsersGroupsRoles:
models.Groups.findAll({
attributes: {
exclude: ['createdAt', 'updatedAt'],
},
include: [
{
model: models.Users,
attributes: {
exclude: ['createdAt', 'updatedAt', 'email', 'password'],
},
through: {
include: [
{
model: models.UsersGroupsRoles,
as: 'UsersGroupsRoles',
},
],
},
},
],
})
But the query fails with TypeError: Cannot read property 'indexOf' of undefined. I suppose it is because the include clause inside through, but then, what is the correct way to include a one-to-many association in an intermediate table?
Thanks!
What about try this?
try {
let groups = await models.Groups.findAll({
attributes: {
exclude: ['id','createdAt', 'updatedAt'],
}
})
const userGroupsPromises = groups.map(group => {
return models.UsersGroups.findAll({
where: {
groupId: group.id
},
include: [{
model: models.User,
attributes: {
exclude: ['createdAt', 'updatedAt', 'email', 'password'],
}
}, {
model: models.UsersGroupsRoles,
}]
})
})
const userGroupsPromiseResult = await Promise.all(userGroupsPromises)
groups = groups.map((group, index) => {
const _group = group.get()
_group.UserGroups = userGroupsPromiseResult[index]
return _group
})
console.log(groups)
} catch (err) {
console.log(err)
}

How can I achieve this SQL QUERY in sequelize (multiple joins and multiple AND/OR)

I've been struggling to achieve this (below SQL statement) in sequelize for a while now with no luck. I initially had to make separate sequelize queries to get the data but that just posed many limitations.
`SELECT "Documents".* FROM "Documents"
INNER JOIN "AccessTypes"
ON "AccessTypes"."id" = "Documents"."accessTypeId"
INNER JOIN "Users"
ON "Users"."id" = "Documents"."userId"
INNER JOIN "Departments"
ON "Departments"."id" = "Users"."departmentId"
WHERE
(("AccessTypes".name != 'private'
AND "Departments"."id" = ${req.decoded.departmentId})
OR "Users".id = ${req.decoded.id})
AND ("Documents"."title" ILIKE '%${searchQuery}%'
OR "Documents"."content" ILIKE '%${searchQuery}%'`
This is as far as I got
var dbQuery = {
where: {
$or: [
{
title: {
$iLike: `%${searchQuery}%`
}
},
{
content: {
$iLike: `%${searchQuery}%`
}
}
]
},
include: [{
model: db.Users,
where: { departmentId: req.decoded.departmentId }
},
{
model: db.AccessTypes,
where: { name: { $ne: 'private'}}
}]
};
db.Documents.findAll(dbQuery)
I still need to fetch another set of documents based on the userId supplied. I feel the way to go will be to perform an 'Include' within an '$or' statement. however my research so far leads me to believe that's not possible.
Here are my models
Access Types
export default (sequelize, DataTypes) => {
const AccessTypes = sequelize.define('AccessTypes', {
name: {
type: DataTypes.STRING,
allowNull: false,
isUnique: true
}
}, {
classMethods: {
associate: (models) => {
// associations can be defined here
AccessTypes.hasMany(models.Documents, {
foreignKey: 'accessTypeId',
onDelete: 'CASCADE'
});
}
}
});
return AccessTypes;
};
Users
export default (sequelize, DataTypes) => {
const Users = sequelize.define('Users', {
username: {
type: DataTypes.STRING,
unique: true,
allowNull: false
},
firstname: {
type: DataTypes.STRING,
allowNull: false
},
lastname: {
type: DataTypes.STRING,
allowNull: false
},
email: {
type: DataTypes.STRING,
unique: true,
allowNull: false,
validate: {
isEmail: true
}
},
password: {
type: DataTypes.STRING,
allowNull: false
},
roleId: {
type: DataTypes.INTEGER,
allowNull: false,
defaultValue: 3
},
departmentId: {
type: DataTypes.INTEGER,
allowNull: false
}
}, {
classMethods: {
associate: (models) => {
// associations defined here
Users.belongsTo(models.Roles, {
onDelete: 'CASCADE',
foreignKey: 'roleId'
});
Users.belongsTo(models.Departments, {
onDelete: 'CASCADE',
foreignKey: 'departmentId'
});
Users.hasMany(models.Documents, {
as: 'documents',
foreignKey: 'userId',
onDelete: 'CASCADE'
});
}
}, ...
Departments
export default (sequelize, DataTypes) => {
const Departments = sequelize.define('Departments', {
name: {
type: DataTypes.STRING,
allowNull: false,
isUnique: true
}
}, {
classMethods: {
associate: (models) => {
// associations can be defined here
Departments.hasMany(models.Users, {
foreignKey: 'departmentId',
onDelete: 'CASCADE'
});
}
}
});
return Departments;
};
and Documents
export default (sequelize, DataTypes) => {
const Documents = sequelize.define('Documents', {
title: {
type: DataTypes.STRING,
allowNull: false
},
content: {
type: DataTypes.TEXT,
allowNull: false
},
userId: {
type: DataTypes.INTEGER,
allowNull: false
},
accessTypeId: {
type: DataTypes.INTEGER,
allowNull: false,
defaultValue: 1
},
docTypeId: {
type: DataTypes.INTEGER,
allowNull: false
}
}, {
classMethods: {
associate: (models) => {
// associations can be defined here
Documents.belongsTo(models.Users, {
foreignKey: 'userId',
as: 'user',
onDelete: 'CASCADE'
});
Documents.belongsTo(models.DocumentTypes, {
foreignKey: 'docTypeId',
onDelete: 'CASCADE'
});
Documents.belongsTo(models.AccessTypes, {
foreignKey: 'accessTypeId',
onDelete: 'CASCADE'
});
}
}
});
return Documents;
};
Any Pointers Will be greatly appreciated
Thanks in Advance
This is quite complex query (in Sequelize way of course), so you need to build it differently than you did. You should use functions like sequelize.col(), sequelize.where(), sequelize.or() and sequelize.and(). Moreover, in order to include the Departments model in the query, you need to use nested include statement in the options object of the findAll query. You can nest the includes as much as you want.
where: sequelize.and(
sequelize.or(
sequelize.and(
sequelize.where(sequelize.col('AccessTypes.name'), '!=', 'private'),
sequelize.where(sequelize.col('Departments.id'), '=', req.decoded.departmentId)
),
sequelize.where(sequelize.col('Users.id'), '=', req.decoded.id)
),
sequelize.or(
{ title: { $iLike: `%${searchQuery}%` } },
{ content: { $iLike: `%{searchQuery}%` } }
)
),
include: [
{
model: db.Users,
include: [ db.Departments ]
},
{
model: db.AccessTypes
}
]
You need to briefly get through documentation of above mentioned functions. In a short, col() creates a proper column selection basing on model name and field, where() creates WHERE statement with use of three attributes - column, condition (comparator) and logic, or() creates OR statement and and() creates AND statement. Both or() and and() can obtain multiple arguments that allows you to create complex statements, like yours.

Sequelize findAll with belongsToMany association

I have two tables related in this way :
League
sequelize.define('league', {
name: {
type: DataTypes.STRING,
},
ownerId: {
type: DataTypes.INTEGER,
}
}, {
classMethods: {
associate: function(models) {
League.belongsToMany(models.user, {
constraints: false,
through: models.UserLeague,
});
}
}
}, {
freezeTableName: true
});
User
sequelize.define('user', {
name: {
type: DataTypes.STRING
},
email: {
type: DataTypes.STRING,
unique: true,
validate: {
isEmail: true
}
},
profile_picture: {
type: DataTypes.STRING
}
}, {
classMethods: {
associate: function(models) {
User.belongsToMany(models.league, {
constraints: false,
through: models.UserLeague,
});
}
}
}, {
freezeTableName: true
});
I would like to get all the leagues that have a certain User in them : I'm doing this at the moment but I get the error column league.users.id does not exist
sequelize.transaction(function (t) {
return models.user.findOne({where: {email: req.query.email}}, {transaction: t}).then(function(user) {
return models.league.findAll({where: {'users.id': user.id}, include: [{model: models.user, as: 'users'}]}).then(function(leagues) {
res.json(leagues);
});
});
});
How could I retrieve the leagues where there is a certain user ?
You should add your where to the included model:
sequelize.transaction(function (t) {
return models.user.findOne({where: {email: req.query.email}}, {transaction: t}).then(function (user) {
return models.league.findAll({
include: [{
model: models.user,
as: 'users',
where: {
id: user.id
},
required: true
}]
}).then(function (leagues) {
res.json(leagues);
});
});
});
Update:
Its' not really nice, but I thinik, there is no better solution:
sequelize.transaction(function (t) {
return models.user.findOne({where: {email: req.query.email}}, {transaction: t}).then(function (user) {
var _leagueIds = [];
return models.league.findAll({
include: [{
model: models.user,
as: 'users',
where: {
id: user.id
},
required: true
}]
})
.each(function (league) {
_leagueIds.push(league.id);
})
.then(function () {
return models.league.findAll({
where: {
id: _leagueIds,
},
include: [{
model: models.user,
as: 'users'
}]
});
})
.then(function (leagues) {
res.json(leagues);
});
});
});

Categories

Resources