Remove Unwanted Unstaged Changes in Tracked Files from a git Repository

This article demonstrates how to discard undesired, unstaged changes to tracked files in a git repository with git checkout so that they do not wind up in your next commit. To discard changes to…

Smartphone

独家优惠奖金 100% 高达 1 BTC + 180 免费旋转




Associations in Sequelize

You wake up with your dream idea. You rush to the computer and flesh out how your paradigm-shifting, earth-shattering application will operate. Your magical wireframes are already luring your mind into dreams of fame and fortune. Then you sit down to the very glamorous task of schema design and database management…and there the fun begins…

We’ve all been there. Schema design for the average developer can be a beast. You think you’ve got it down only to realize your garbled calls to the database are bringing you plates of tossed spaghetti. You re-design, you add pivot tables, and you weep uncontrollably.

Programmers know when it’s time to look for better solutions, and a great solution out there for database management is Sequelize, a multi-dialect ORM for Node.JS. If you’re not familiar with it you can find their docs here:

A common complaint about Sequelize is that their docs are much like the spaghetti I mentioned earlier. In other words, they’re a mess. I don’t mean to throw stones here. I’m sure building Sequelize itself was no small task, and this team certainly has better things to do than to constantly be improving the docs. They’re too busy improving the library itself. Love you guys!

Are they gone? Phew. Now back to trashing their docs

You can manage with the basic tasks of model definition and validations, but the wheels start to come off when you start messing around with associations. And that, ladies and gentlemen, is what brings us here today. I’m going to talk a little bit about associations and magic methods. Every time I look them up in the docs, I end up befuddled. Google searches turn up posts where people have basically cut and pasted the docs and used their own obtuse words to explain them. So if you find yourself in the same spot, hopefully this post will conclude your search.

Let’s take the example of a database with the following:

Now let’s figure out our associations. What are our options? There’s One-To-One, One-To-Many, and Many-To-Many. It makes it easier to talk about when we think of the models as Targets and Sources. In Sequelize, these translate to:

One-To-One:

Model.belongsTo

Model.hasOne

Wait a minute…those two are interchangeable! What do I use when? The fact of the matter is that you should use what makes more sense to you. It really boils down to semantics. In our examples, it would make slightly more sense to say that a Project has a WorkSite as opposed to a WorkSite belonging to a Project. To make it even clearer: Does a person have a head or does a head belong to a person? While they are both true, saying a head belongs to a person just sounds weird. Like she’s got a head in her backpack as to one sitting on her neck. These examples do show however that if you are dealing with more abstract models, your choice can help define the relationship for the reader. If you’re dealing with bar and baz as opposed to heads and people, your decision can help the reader conceptualize the relationship a bit better.

Now we’ve gained access to some magic methods: get and set. These add another layer of abstraction. Instead of:

you can do:

My oh my. That’s a bit tidier, isn’t it?

Oftentimes, if you have an association you’ll need the data in the associated instance.

Here’s where eager loading comes in. No need to make an additional call, you’ll just need to take advantage of the ‘includes’ option:

or my favorite:

Now that’s some tasty spaghetti!

One-To-Many and Many-To-Many:

Model.hasMany

Say we’re working with an arrangement where one User will have many Projects. To simply add a userId to our projects we can say:

As above, we can now getProjects and setProjects a lá:

Voilá!

Model.belongsToMany

You still with me? ’Cause things are about to get crazy… Tables are cheap my friends and if you find yourself doing backbends to make your tables work it’s likely time for a pivot or join table. Time to start cooking up some tasty API spaghetti…

In the spirit of collaboration we’ve decided to build some teams. So now our Projects will have many Users. When you’re using belongsToMany you are building the join table with your association by use of ‘through’:

Simply by naming the association you have generated the UserProject table which holds just the ids of the related instances. Keep in mind that the rows in this join table do not have their own individual ids and the Project model does not have userId or vice versa.

If you want your join table to have individual ids or you’d like to add unique fields of information you’ll need to create the join table on its own first, and then make your associations:

You’ve got the full magic toolbox in effect. Now you can getUsers, setUsers, addUser, addUsers, getProject, setProject, addProject, addProjects. Now the possibilities are endless, and sadly it’s time for me to return you to:

The “Associating Objects” and “Creating With Associations” sections are where you can see examples of truly harnessing the power of associations. With the tools there, you’ll be able to make selective calls to the database so you won’t have to wade through quite as much nested data, or one more time: API spaghetti. Yum!

So that’s it gang. Hopefully I’ve demystified associations a little bit. I know it was one of the hardest aspects of Sequelize to wrap my head around, and I still don’t pretend to be a master. That title I will leave for Mick Hansen, Jan Meier, and the rest of the Sequelize team. I meant no disrespect regarding the docs. Sequelize is a fantastic library that allows us mere mortals to grapple with SQL in a far easier way. Kudos to the Sequelize team, and keep up the good work!

Add a comment

Related posts:

Apa jadinya Millenials tanpa Jaringan Internet?

Kalian kesel nggak sih kalau kalian udah enak-enak ngopi, tiba-tiba wi-fi nya rusak atau jaringan internetnya lambat? Ngeselin banget nggak sih? Rasanya saat ini ada yang kurang kalau tempat yang…

The REAL Most Interesting Man In The World

Some people seem to pop up everywhere you look? For me, that person is Antoine de Saint-Exupéry, who died in 1944. I was first struck by a quote of his in Yvon Chouinard’s book, Let My People Go…

Viewpoint Interviews

For my final post I wanted to partake in multiple small interviews with a handful of University at Buffalo students who only speak one language and ask them some questions to get a bit of perspective…