What methods/mixins sequelize adds to the models when an association is made?

前端 未结 2 498
傲寒
傲寒 2021-02-04 17:43

While going through the sequelize docs, more specifically the documentations about associations, I see that the guide casually shows the reader methods such as setTasks()<

相关标签:
2条回答
  • 2021-02-04 18:21

    The documentation about associations you linked, although hosted in an address called docs.sequelize.js, isn't the real sequelize docs (as in fully covered docs with all details that a good documentation usually provides). That is more like a tutorial / guide for starters.

    The real sequelize docs are found by clicking on the "Reference" link available in the side menu of the links you mentioned (and it took me quite a while to find that - it doesn't even look like a clickable thing IMO).

    The parts you're interested here are these:

    • Sequelize docs for BelongsTo type of associations: here
    • Sequelize docs for BelongsToMany type of associations: here
    • Sequelize docs for HasMany type of associations: here
    • Sequelize docs for HasOne type of associations: here

    Understanding the docs

    Since the docs linked above can be very confusing, here is an explanation to assist you to understand the docs.

    Let's assume, for example, that we have a belongs to many association between Person and Hypothesis. Note that their plural forms, People and Hypotheses, are automatically inferred by Sequelize. This magic is done under the hood by the awesome library called inflection - see How do plurals work in Sequelize? for more details.

    // Assuming that the models Person, Hypothesis and Person_Hypothesis are already defined
    Person.belongsToMany(Hypothesis, { through: Person_Hypothesis });
    Hypothesis.belongsToMany(Person, { through: Person_Hypothesis });
    

    And we want to use the Sequelize docs for BelongsToMany type of associations to learn what methods were automatically added to instances of the Person and Hypothesis models. There, we can find the following table:

    To understand what this table means, recall that in the beginning of that page of the docs it says that "In the API reference below, add the name of the association to the method". The most confusing part of this is that it's not so clear when you should add the singular version of the name and when you should add the plural version. But although the docs do not make this clear, I assure you that you can just use common sense to guess. And if you think both versions could make sense (for example, for add), be surprised that actually both versions are available. Therefore, from the table above, we can conclude:

    • Methods added to instances of Person models:

      • addHypothesis()
      • addHypotheses()
      • countHypotheses()
      • createHypothesis()
      • getHypotheses()
      • hasHypothesis()
      • hasHypotheses()
      • removeHypothesis()
      • removeHypotheses()
      • setHypotheses()
    • Methods added to instances of Hypothesis models:

      • addPerson()
      • addPeople()
      • countPeople()
      • createPerson()
      • getPeople()
      • hasPerson()
      • hasPeople()
      • removePerson()
      • removePeople()
      • setPeople()

    Another way to figure this out without room for doubt is by checking the Sequelize source code itself, namely here, where we can find:

    this.accessors = {
        get: 'get' + plural,
        set: 'set' + plural,
        addMultiple: 'add' + plural,
        add: 'add' + singular,
        create: 'create' + singular,
        remove: 'remove' + singular,
        removeMultiple: 'remove' + plural,
        hasSingle: 'has' + singular,
        hasAll: 'has' + plural,
        count: 'count' + plural
    };
    

    Note: although it might seem counter-intuitive, in fact both methods addPerson() and addPeople() mentioned above work with the same parameters, which can be either a single value or an array. In other words, the methods add and addMultiple from the source code are actually the same, in the end. The same applies to remove() and removeMultiple(), and hasSingle() and hasAll().

    Hopefully with this you can now understand what the Sequelize docs really mean with those tables.

    If you prefer to check the source code directly, analogously to what I showed above, these are the relevant lines for the other kinds of associations:

    • BelongsTo: here

      this.accessors = {
          get: 'get' + singular,
          set: 'set' + singular,
          create: 'create' + singular
      };
      
    • HasOne: here

      this.accessors = {
          get: 'get' + singular,
          set: 'set' + singular,
          create: 'create' + singular
      };
      
    • HasMany: here

      this.accessors = {
          get: 'get' + plural,
          set: 'set' + plural,
          addMultiple: 'add' + plural,
          add: 'add' + singular,
          create: 'create' + singular,
          remove: 'remove' + singular,
          removeMultiple: 'remove' + plural,
          hasSingle: 'has' + singular,
          hasAll: 'has' + plural,
          count: 'count' + plural
      };
      
    0 讨论(0)
  • 2021-02-04 18:29

    To get a listing of the added methods try:

        const model = %yourSequelizeModel%
        for (let assoc of Object.keys(model.associations)) {
          for (let accessor of Object.keys(model.associations[assoc].accessors)) {
            console.log(model.name + '.' + model.associations[assoc].accessors[accessor]+'()');
          }
        }
    

    Credit goes to https://gist.github.com/Ivan-Feofanov/eefe489a2131f3ec43cfa3c7feb36490

    To adjust the association names use "as" option:

    Model.hasOne(models.series_promotions, { as: 'seriesPromotions' });
    

    which changed the association method name from:

    series.getSeries_promotion()
    series.setSeries_promotion()
    series.createSeries_promotion()
    

    to

    series.getSeriesPromotions()
    series.setSeriesPromotions()
    series.createSeriesPromotions()
    

    based on the snippet above.

    0 讨论(0)
提交回复
热议问题