Sequelize Query take all values in where condition - node.js

I have an array=[1,2,3]
Only 1 & 2 are in the database under the column ID.
When I perform a query using WHERE IN it gives me result of 1 & 2.
What I want to do is if all data matches then show me the result otherwise null
I am using Sequelize. How can this be done?
Query:
Models.Question.findOne({
where: {
id:1
},
include: [{
model: Models.QuestionOptions,
as: 'options',
required: true,
where: {
id:[1,2,3]
}
}]
});
expect result Null because only 1 & 2 are in DB

require:true means INNER JOIN. In other words it will only return lines with existing associations(If the condition is also true of course). You should remove it if you want to get all lines(Left Join) even if there is no corresponding association

You can achieve this using group and having clause.
Models.Question.findOne({
attributes: ["id"],
where: {
id:1
},
group: ['id'],
having: sequelize.where(sequelize.fn('count', sequelize.col('options.id')), {
[sequelize.Op.gte]: 3,
}),
include: [{
model: Models.QuestionOptions,
as: 'options',
attributes: [],
required: true,
where: {
id:[1,2,3]
}
}]
});

Related

Adding order clause in queries with nested association in Sequelize

I trying to fetch the assessment details for a class in which assessment_test model has association with student_assessment_test model(hasMany). I want the fetched result ordered according to the marks obtained by student. I am trying the below method but it doesn't seem to be working. Please let me know the correct method for such queries.
const assessmentDetails = await Entity.assessmentTest.findOne({
where: { id: assessmentId, status: 1 },
attributes: [
'id',
'sectionId',
'assessmentDate',
'assessmentTitle',
'totalPoints',
],
include: [
{
association: 'assessmentTestDetails',
where: { status: 1 },
attributes: ['marksObtained', 'percentage', 'testStatus'],
required: true,
order: [['marksObtained', 'ASC']],
include: [
{
association: 'student',
where: { status: 1 },
attributes: ['studentName'],
required: true,
},
],
},
],

left join on same table in sequelize

I want to write following query in sequelize but Not able to understand how to do.
SELECT * FROM RegisterUser AS RegisterUser
LEFT OUTER JOIN Notification as Noti ON PM_UserID = Noti.ReceiveID
LEFT OUTER JOIN RegisterUser AS RegisterUser1 ON
Noti.SenderId = RegisterUser1.PM_UserID
WHERE RegisterUser.PM_UserID = ReceiveID
I have written below query as a single left join and it works fine.
RegisterUser.findAll({
include: [
{
model: Notification,
as: 'NotificationrecipientId',
required: false,
},
],
raw: true });
And my assciotion is as follow:
db.RegisterUser.hasMany(db.Notifications, { as: 'NotificationrecipientId', foreignKey: 'ReceiveID' });
Sender ID as well in Register User table.
For that you have define one more association :
db.Notification.belongsTo(db.RegisterUser, { as: 'Sender', foreignKey: 'SenderId' });
and then use it like :
RegisterUser.findAll({
include: [{
model: Notification,
as: 'NotificationrecipientId',
required: false,
include: [{
model: RegisterUser,
as: 'Sender', // <---- HERE
required: false,
}, ]
}, ],
raw: true
});

unknown column in field list sequelize

I'm trying to perform the following query using Sequelize:
db.Post.findAll({
include: [
{
model: db.User,
as: 'Boosters',
where: {id: {[Op.in]: a_set_of_ids }}
},
{
model: db.Assessment,
as: 'PostAssessments',
where: {UserId: {[Op.in]: another_set_of_ids}}
}
],
attributes: [[db.sequelize.fn('AVG', db.sequelize.col('Assessments.rating')), 'average']],
where: {
average: 1
},
group: ['id'],
limit: 20
})
But I run to this error: "ER_BAD_FIELD_ERROR". Unknown column 'Assessments.rating' in 'field list', although I do have table "Assessments" in the database and "rating" is a column in that table.
My Post model looks like this:
const Post = sequelize.define('Post', {
title: DataTypes.TEXT('long'),
description: DataTypes.TEXT('long'),
body: DataTypes.TEXT('long')
}, {
timestamps: false
});
Post.associate = function (models) {
models.Post.belongsToMany(models.User, {as: 'Boosters', through: 'UserPostBoosts' });
models.Post.hasMany(models.Assessment, {as: 'PostAssessments'});
};
What am I doing wrong?
It seems like this problem surfaces when we have a limit in a find query where associated models are included (the above error doesn't show up when we drop the limit from the query). To solve that, we can pass an option subQuery: false to the find. (https://github.com/sequelize/sequelize/issues/4146)
This is the correct query in case anyone comes across the same problem:
db.Post.findAll({
subQuery: false,
include: [
{
model: db.User,
as: 'Boosters',
where: {id: {[Op.in]: a_set_of_ids }}
}
,{
model: db.Assessment,
as: 'PostAssessments',
where: {UserId: {[Op.in]: another_set_of_ids}}
}
],
having: db.sequelize.where(db.sequelize.fn('AVG', db.sequelize.col('PostAssessments.rating')), {
[Op.eq]: 1,
}),
limit: 20,
offset: 2,
group: ['Post.id', 'Boosters.id', 'PostAssessments.id']
})
Error is with this one :
models.sequelize.col('Assessments.rating'))
Change it to
models.sequelize.col('PostAssessments.rating')) // or post_assessments.rating
Reason : You are using the alias for include as: 'PostAssessments',.

Sequelize query on join table

I am trying to querying a join table using sequelize:
Here is the model:
db.client.belongsToMany(db.user, {
through: db.clientUser,
onDelete: 'cascade',
});
db.user.belongsToMany(db.client, {
through: db.clientUser,
});
and this is what I am trying to do:
db.user.findAll({
where: {
group_id: 1,
},
include: [{
model: db.clientUser,
where: {
is_manager: 1,
}
}],
raw: true,
})
However I get the following error: client_user is not associated to user!
Any idea what could be the cause of this issue?
You declared a relationship between client from user through clientUser. Although pedantic, its complaint is technically correct: there is no explicitly declared relationship declared between client and clientUser. Nor should there be: your belongsToMany relationship should take care of that. Your query can be adjusted to work with this relationship.
Note: I don't know what tables group_id and is_manager are found in. They may need to be shuffled around.
db.user.findAll({
where: {
group_id: 1,
},
include: [{
model: db.client,
through: {
where: {
is_manager: 1, // Assuming clientUser.is_manager?
},
}],
raw: true,
})

Nested include with offset and limit Sequelize

Is anyone successful using nested include along with Limit and Offset in Sequelize. I'm trying to implement server side paging using the Sequelize, can anyone show me any reference. I'm using Sql Server database. I see that the query is being converted as sub query along with joins when I try to do this. Has anyone got
{where: query.activity,
attributes: [...activityAttributes, 'LastModifiedUserID', 'LastModifiedDateUTC', 'SPIStatus'],
include: [
{
model: Issue,
where: query.issue,
attributes: issueAttributes,
include: [{
model: Product,
where: query.product,
attributes: productAttributes
},
{
model: IssueExtendedAttribute,
where: {$and: query.issueExtendedAttributes},
required: !!query.issueExtendedAttributes
}]
}],
offset: 10,
limit: 10}
You need to add
subQuery: false;
ex:
{
subQuery: false,
where: queryObj,
include: [{
model: db.A,
where: AQueryObj,
include:[{
model: db.B,
where: BQueryObj
},{
model: db.C,
where: CQueryObj
}]
}],
offset: offset,
limit: limit
}
Check this link to get more information

Resources