Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query based on included data in Sequelize

I have a table for people with a self-association so people can have parents/children/cousins/etc.

const People = sequelize.define('People', {
  gender: Sequelize.STRING,
  name: Sequelize.STRING,
  age: Sequelize.INTEGER
})

const Relationships = sequelize.define('Relationships')
Items.belongsToMany(Items, { through: Relationships, as: 'relationships' })

I want to be able to select the data in two ways:

1. Select all of the relations of a person who are the age of 21

// Returns all of johns relatives who are 21
return People.findOne({
  where: { name: 'John' },
  include: [{
    required: false,
    model: Items,
    as: 'relationships',
    where: { age: 21 }
  }]
})

2. Select all of the people who have a relation who is the age of 21. This will need to accept multiple queries like: Select all of the people who have a relative who is 21 or/and a Male.

Any ideas?

like image 770
wazzaday Avatar asked Nov 30 '25 02:11

wazzaday


1 Answers

For the 1st question: Select all of the relations of a person who are of age 21. Your query is correct.

return People.findOne({
  where: { name: 'John' },
  include: [{
    required: false,
    model: People,
    as: 'relationships',
    where: { age: 21 }
  }]
});

For the 2nd query: To select all of the people who have a relation who is the age of 21 or/and a Male.

People.findAll({
  include: [{
    required: true,
    model: People,
    as: 'relationships',
    where: {
      $or: [
        { age: 21 },
        { gender: 'Male' }
      ]
    }
  }]
});

Hope this will be helpful to anyone who comes across the post

like image 157
Hassan Rehan Avatar answered Dec 02 '25 19:12

Hassan Rehan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!