skip to Main Content

I have a sequelize model called staff. One of the staff columns is called locations which holds the id’s of all the locations this staff is available at. I want to create a query that uses a Location ID to get all staff active at that location. How can I do that using the ORM?

3

Answers


  1. In Sequelize, you can perform a query to filter staff based on their locations using the include and where options in your query.

    const staff = await Staff.findAll({
      include: [
        {
          model: Location,
          as: 'locations',
          where: { id: locationId },
          through: { attributes: [] }
        }
      ]
    });
    
    Login or Signup to reply.
  2. const findStaff = await StaffModel.findAll({
    where: {
    locationId: "your locationId"
    }
    })

    Login or Signup to reply.
  3. Assuming I have understood your question correctly and your locations column contains CSV data, then you need to use FIND_IN_SET()

    Staff.findAll({
        where: sequelize.where(sequelize.fn('FIND_IN_SET', locationId, sequelize.col('locations')), {[Op.gt]: 0})
    })
    

    A better option would be to normalize your data as this query is non-SARGable.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search