sequelize icon indicating copy to clipboard operation
sequelize copied to clipboard

HOOKs and INCLUDE

Open cybernadinou opened this issue 11 years ago • 21 comments

Hi everybody,

I have added some hook on my models but when this models are include in other models, their don't call the hooks. For example :

return models.company.findAll({
    where : { idUser : idUser },
        include : [ {
            model : models.ticket , as : 'tickets',
            include : [{
                model : models.access , as : 'access' ,
                include : [
                    { model : models.event , as :'events' } ,
                    { model : models.eventPricing , as : 'priceItems' }
                ]
            }]
        }]
    }).then(function(transactions){
        return transactions;
    }).catch(function(error) {
        return error;
});

In this example I have a hook "afterFind" on my models "event" and "eventPricing" but it doesn't call my hook afterFind. I tried to use this hooks: 'beforeFindAfterExpandIncludeAll' but its before Find and me I want it afterFindExpandIncludeModels or something like that I would like to call my hooks for each models event and eventPricing. Does anyone has already been faced to this problem ? Should I use an other Hook to do my job ? If I should, which one plz ? And I'm working with Sequelize 2.0 but I didn't find other hooks available for with Sequelize 3.0 so. Want to know if I forgot something or if you got a quick solution to fix it, otherwise I'll figured out with several requests but I prefer to do that in just one :)

Thanks in advance for your help.

cybernadinou avatar Oct 08 '15 15:10 cybernadinou

This is a known issue, one that has bugged me aswell. Changing it probably constitutes a breaking change.

mickhansen avatar Oct 08 '15 17:10 mickhansen

+1 why would it be a breaking change ?

chilipote avatar Oct 08 '15 17:10 chilipote

Users will have grown used to it not happening, at it suddenly happening might break for users.

mickhansen avatar Oct 08 '15 17:10 mickhansen

Well, I guess I'll figure out. Thanks

cybernadinou avatar Oct 08 '15 19:10 cybernadinou

@mickhansen revisit this for 4.0? Maybe hooks: true?

felixfbecker avatar Jun 18 '16 13:06 felixfbecker

I am currently ran into situation when the hooks are important, as I store JSON data/arrays in normal TEXT field, with conversions from string to JSON and otherway using before create and after find hooks. It feels weird that hooks are not called when a model including another model, and makes the automatic parsing impossible. Please at least consider allowing it explicitly like @felixfbecker suggested. this way it won't break any existing code.

aviranco avatar Jul 06 '16 17:07 aviranco

Or hooks: false to get the old behaviour back

felixfbecker avatar Jul 06 '16 18:07 felixfbecker

I must mention this is a big issue IMHO since hooks should be a reliable way to perform actions on each-model interaction across the application, and to walkaround this there is need to re-implement the same hooks after performing every query "by hand" and being aware of the exact data structure. I assume there is no other callback mechanism called after every query?

aviranco avatar Jul 06 '16 18:07 aviranco

@aviranco I think there is something like runHook() which is the best workaround for now

felixfbecker avatar Jul 06 '16 18:07 felixfbecker

@felixfbecker Lets revisit yet, although it's near impossible to get a completely uniform experience between regular find calls and include calls.

For include.separate it could work very well though.

@aviranco Your case would be better solved using setters/getters on attributes or defining a custom json datatype.

mickhansen avatar Jul 07 '16 06:07 mickhansen

@mickhansen Thanks for the advice. I am using now getters/setters, but I still have to use the beforeValidate hook since if I pass the data I want as JSON object, and the field type is TEXT it fails validation when trying to add entry (I am using mariaDB/mysql that lacks of JSON data type).

If there is another solution that will help me avoid using the beforeValidation I would love to hear it.

aviranco avatar Jul 07 '16 11:07 aviranco

I am having the same situation as @aviranco and indeed the setters/getters seem to be a solution. Does doing this have any effect on performance?

Also, I couldnt find the reference to include.separate on the docs, could someone link it? :+1:

Thanks

ybrodsky avatar Jul 14 '16 15:07 ybrodsky

Just hit this issue, its been 6 years, any chance we've revisited this. I think the hooks: true works well

@mickhansen - are you still using getters/setters?

rosscoombes avatar May 20 '21 11:05 rosscoombes

I just bumped into this issue as well, it doesn't make sense to not call hooks for included models in my opinion.

Bossieh avatar Jun 16 '21 14:06 Bossieh

I ran into this issue. Still no news on how to deal with it? The getter I would need is async, hence my usage of hooks.

luciomr avatar Jun 18 '21 14:06 luciomr

I think adding the attribute hooks with default set on false is the best option. For v7, it might make more sense to switch the default around.

I suppose we should add this attribute to the Includable object, right? Meaning, the API would look like this:

company.findAll({
    include: [{
        hooks: true // <---
        model: models.ticket,
        as: 'tickets',
        include: [{
            model: models.access,
            as: 'access',
            include: [{
                    model: models.event,
                    as: 'events'
                },
                {
                    hooks: true, // <---
                    model: models.eventPricing,
                    as: 'priceItems'
                }
            ]
        }]
    }]
})

Keimeno avatar Jun 18 '21 14:06 Keimeno

What's the timeline for a possible integration of this issue?

svennergr avatar Oct 05 '21 13:10 svennergr

I needed to run the afterFind hook on all my included models, hopefully someone can find this helpful:

const handleChildrenAfterFindHook = async (instances, options, level = 0) => {
    if (!instances) return Promise.resolve();

    if (Array.isArray(instances)) {
        return Promise.all(
            instances.map((instance) => {
                const { options: instanceOptions } = instance.constructor;
                return handleChildrenAfterFindHook(
                    instance,
                    instanceOptions,
                    level
                );
            })
        );
    }

    const instance = instances;
    const { constructor } = instance;

    /**
     * Root model will have already run their "afterFind" hook.
     * Only run children "afterFind" hooks.
     */
    if (level >= 1) {
        await constructor.runHooks('afterFind', instance, options);
    }

    const { associations } = constructor;
    const associatedNames = Object.keys(instance).filter((attribute) =>
        Object.keys(associations).includes(attribute)
    );

    if (associatedNames.length) {
        const childInstances = associatedNames.map((name) => instance[name]);
        return handleChildrenAfterFindHook(childInstances, options, level + 1);
    }

    return Promise.resolve();
};

sequelize.addHook('afterFind', handleChildrenAfterFindHook);
models.sequelize = sequelize;

aedenmurray avatar Dec 01 '21 20:12 aedenmurray

@aedenmurray - you are the best! Here is the sequelize-typescript version of this:

  @AfterFind
  static async afterFindForIncludedEntities(instances, options, level = 0) {
    if (!instances) return;

    if (Array.isArray(instances)) {
      return Promise.all(
        instances.map((instance) => {
          const { options: instanceOptions } = instance.constructor;
          return this.afterFindForIncludedEntities(instance, instanceOptions, level);
        }),
      );
    }

    const instance = instances;
    const { constructor } = instance;

    /**
     * Root model will have already run their "afterFind" hook.
     * Only run children "afterFind" hooks.
     */
    if (level >= 1) {
      await constructor.runHooks('afterFind', instance, options);
    }

    const { associations } = constructor;
    const associatedNames = Object.keys(instance).filter((attribute) => Object.keys(associations).includes(attribute));
    if (associatedNames.length) {
      const childInstances = associatedNames.map((name) => instance[name]).filter(v => !!v);
      return this.afterFindForIncludedEntities(childInstances, options, level + 1);
    }
  }

The careful reader might have noticed the extra .filter(v => !!v) while collecthing childInstances -- this is to prevent to go deep in case of optional nested entities.

iamFIREcracker avatar Mar 31 '23 08:03 iamFIREcracker

The beforeFind version, little different since beforeFind hook only passes options. I therefore explore the included models on which I perform a runHooks. Not sure of the robustness but seems to work well for me.

const handleChildrenBeforeFindHook = async (options, level = 0) => {
        if (!options) return Promise.resolve();

        /**
         * Root model will have already run their "beforeFind" hook.
         * Only run children "beforeFind" hooks.
         */
        if (level >= 1 && options.model) {
            await options.model.runHooks('beforeFind', options);
        }

        if (options.include) {
            return Promise.all(
                options.include.map((includeOptions) => {
                    return handleChildrenBeforeFindHook(includeOptions, level + 1);
                })
            );
        }

        return Promise.resolve();
};

sequelize.addHook('beforeFind', handleChildrenBeforeFindHook);

What are the perf downsides though ?...

AndrieuGirard avatar May 15 '23 13:05 AndrieuGirard