Sequelize nested were when the subject of the include is possibly null

414 Views Asked by At

In my models I have a User which belongsTo({ model: Company, as: 'company' }) (and conversely Company hasMany({ model: User, as: 'members' }))

I have constructed a query as follows

const query = {
  where: { onboardingState: 'pending' },
  include: [
    {
      model: Company,
      where: { suspendedAt: { [Op.eq]: null } }
    }
  ]
}

const users = await User.findAll(query)

This works fine if the user has an associated company. But there is an edge case (admin users) where the user does not have an associated company, and in that case the findAll query returns []

How do I structure my query to only require company.suspendedAt == null if the company exists, and to ignore the company where clause if the company does not exist?

0

There are 0 best solutions below