Naoto Ida
Naoto Ida

Reputation: 1295

Getting related data through object_2_object table with Sequelize

I have an Pet object, which belongs to a Species through SpeciesToPet.

I have the following definitions with Sequelize.

const Pet = sequelize.define(`pet`, {
  id: {
    type: Sequelize.INTEGER
  }
  ...
})

const SpeciesToPet = sequelize.define(`speciesToPet`, {
  speciesId: {
    type: Sequelize.INTEGER
  },
  petId: {
    type: Sequelize.INTEGER
  }
})

const Species = sequelize.define(`species`, {
  id: {
    type: Sequelize.INTEGER
  }
})

Now, with Pet.belongsToMany(Species, { as: 'species', through: SpeciesToPet,foreignKey: 'petId', otherKey: 'speciesId' }) I can get the Species which the Pet belongs to, but I want to be able to get the Pets in the same Species.

How can I define a relationship to obtain those values?

Upvotes: 0

Views: 46

Answers (1)

Yrysbek Tilekbekov
Yrysbek Tilekbekov

Reputation: 2775

You should just define Species->Pet relation:

Species.belongsToMany(Pet, { as: 'pets', through: SpeciesToPet});

Upvotes: 1

Related Questions