Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

249
Views
Sequelize 'where' on parent and child when parent hasMany childs

I have 2 models:

class User extends Model {
    static associate(models) {
      User.hasMany(models.Role, {
        foreignKey: 'userId'
      });
    }
  };
  User.init({
    firstname: {
      type: DataTypes.STRING,
    },
    lastname: {
      type: DataTypes.STRING,
    },
    allowedApps: {
      type: DataTypes.ENUM({
        values: Object.keys(PORTALS)
      }),
      allowNull: false
    }
  }, {
    sequelize,
    paranoid: true,
    modelName: 'User',
  });

class Role extends Model {
    static associate(models) {
      Role.BelongsTo(models.User, {
        foreignKey: 'userId'
      });
    }
  };
  Role.init({
    type: {
      type: DataTypes.STRING,
      unique: true
    },
    name: DataTypes.STRING,
    userId: {
      type: DataTypes.INTEGER,
      allowNull: false,
    }
  }, {
    sequelize,
    paranoid: true,
    modelName: 'Role',
  });

I would like to get all users where the firstname OR the role type matches a certain condition. Something like:

User
    .findAndCountAll({
        where: {
            $or: [
         {
            firstname: "John Doe"
         },
         {
            "$Role.type$": "Admin"
         }
       ]
        },
        include: [{
            model: Role,
        }],
    }).limit=10,offset=0
    .then(users => res.status(200).send(users))
    .catch(error => {
        return res.sendStatus(500);
    });

above query giving me error: "SequelizeDatabaseError: Unknown column 'Role.type' in 'field list'"

I want to search through child model when it has one to many relationship having my limit and offset intact.Same query would give me success if user would have HasOne relation with role. This is just an example code of what I try to achieve so please ignore any typos and silly mistakes.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

After some digging:

await User.findAll({
where: {
            $or: [
         {
            firstname: "John Doe"
         },
         {
            "$Role.type$": "Admin"
         }
       ]
        },
  include: {
    model: Role,
    as: 'Role',
    required: false
  }
});

However, it doesn't make logical sense to select Users that have no associated Role (required: false), while querying such Users with a property that exists on Role ($or: $Role.type$). If we set Required = true, then we violate your initial condition

firstname OR the role type matches a certain condition.

The following addresses this problem:

await User.findAll({
  include: {
    model: Role,
    required: false
  }
})
.then(
  users => users
    .filter(user => user?.firstName === "John Doe" || user.role?.type === 
    "Admin");
);
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!