Sequelize - How return rows only if included model has at least one record

Viewed 148

I want to this query in Sequelize:

const results = await WorkflowAssignation.findAndCountAll(
                        {
                            limit: limit, 
                            offset: offset, 
                            where: 
                                { 
                                    userId: userIds, 
                                    status: status
                                }, 
                            include: [ 
                                { 
                                    model: WorkflowStepAssignation,
                                    include: [ 
                                        { model: WorkflowStepAssignationHasUser, include: [ users ]}
                                    ] 
                                }, 
                                { model: users } 
                            ], 
                            distinct: true, 
                            order: [ [ 'createdAt', 'DESC'], [ { model: WorkflowStepAssignation, as: "steps" }, 'stepNumber', 'ASC' ] ]  
                        });

The problem is that I need to return only WorkflowAssignation if the WorkflowStepAssignationHasUser table contain at least 1 record with the value passed as parameter for userid.

if I used a where in this line { model: WorkflowStepAssignationHasUser, include: [ users ]} it will still return all the WorkflowAssignation with only the steps that has the userId value and that's not what I want.

It is like I want to return all the WorkflowAssignation including all the tables but only if in WorkflowStepAssignation -> WorkflowStepAssignationHasUser has the users in the parameters.

Relations are:

WorkflowAssignation

has Many

WorkflowStepAssignation

has Many

WorkflowStepAssignationHasUser (has a userId column)

0 Answers
Related