Skip to content

Instantly share code, notes, and snippets.

@jbracht
Last active November 2, 2023 16:23
Show Gist options
  • Save jbracht/1778e93ced532b902fc49d70a743ffb8 to your computer and use it in GitHub Desktop.
Save jbracht/1778e93ced532b902fc49d70a743ffb8 to your computer and use it in GitHub Desktop.

About Sequelize "Magic Methods"

Defining relationships between models in Sequelize will create some "magic methods" for you. But what the heck are they, where the heck do they come from, and how do I know they even exist??

If you want to see the magic methods, try this out:

let user = await User.findByPk(1);
console.log('stuff on user: ', user.__proto__);
// ^^ that will list out "magic methods" available on 'user'

Speaking of some of these ~ ~ magic methods ~ ~ in Sequelize, you might be wondering how it did that. Besides logging out all the methods you can call, they are also listed in the source code (https://github.com/sequelize/sequelize/tree/master/lib/associations). Under each type of association, you can ctrl+f for "accessors" and find a list of what the methods will be called. But here's a preview of what you get for each type of relationship:

Belongs-to-many:

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}`
};

Belongs-to:

this.accessors = {
      get: `get${singular}`,
      set: `set${singular}`,
      create: `create${singular}`
};

Has-many:

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}`
};

Has-one:

this.accessors = {
      get: `get${singular}`,
      set: `set${singular}`,
      create: `create${singular}`
};

So for example, if you have a relationship Owner.hasMany(Pet), you can look at the 'has-many' accessors, and those will be available to Owner (in relation to Pet). Aka: I can grab an owner and say someSpecificOwner.addPet(someSpecificPet) because I can see in the 'has-many' accessors, there's a line for add: 'add${singular}' that I can use if I want to add a Pet to an Owner.

:) Happy coding yall

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment