How to override a relationships routes?

Hello guys,

I have a location model that have a parent location field. In other terms, a location can have a parent location and can have multiples child locations. There is a belongTo and hasMany relationship defined here.

Location.associate = (models) => {
  Location.belongsTo(models.location, {
      foreignKey: {
        name: 'parentIdKey',
        field: 'parent_id',
      },
      as: 'parent',
    });
  Location.hasMany(models.location, {
      foreignKey: {
        name: 'parentIdKey',
        field: 'parent_id',
      },
      as: 'parentLocations',
    });

}
    

I want when editing or creating a location, to only populate as a parent location, locations meeting specific criteria.

Thank for your help!

Hi @Joel_Alexandre_Khang ,

It might be more interesting to use sequelize hooks in your case: Hooks | Sequelize
Let me know if it’s what you are looking for :pray:

Hi @vince
As it’s a belongTo relationship field, it’s going to be a dropdown and i want to only query locations with a specific types. Is it possible with hooks as well ?

Oh okey my bad I misunderstood your question the first time.
You should be able to achieve what you want by overriding the default list route (you can do it just for the dropdown case). If you look at the request you will see 2 query variables that are added in this case: context[record][type] and context[record][id] which contains the type of record and the id of the record being edited :wink: