Home > other >  Am I misunderstanding how foreign keys work? Using Sequelize
Am I misunderstanding how foreign keys work? Using Sequelize

Time:01-26

Let's say I have two tables.

Animals:

animal_Id name color
1 Mouse Yellow
2 Elephant Green
3 Mouse Red
4 Bear Purple

Zoo:

cage_Id size animal_Id (foreign key)
1 Large 2
2 Small 1
3 Small 3

Am I right in assuming that I could create code which would:

  • Allow a user to view the Zoo.
  • Select a small cage within it: 2.
  • Be told that the cage contains a Mouse, yellow.
  • Or select an animal and place them in a cage (size) of their choice, which would result in a new 'Zoo' row:
cage_Id size animal_Id (foreign key)
4 Large 4

If yes, then to use this with Sequelize, I'd need a one-to-one relation right? My code would basically look like:

db.cage = require("../models/cage.model.js")(sequelize, Sequelize);
db.animal = require("../models/animal.model.js")(sequelize, Sequelize);

db.cage.hasOne(db.animal);
db.animal.belongsTo(db.cage);

And I wouldn't have to go into the model and edit in the foreign key reference.

I tried db.cage.hasMany(db.animal); which absolutely didn't work. Trying to see if my current thinking is correct. Thanks!

CodePudding user response:

Your understanding is correct, a one-to-one relationship is appropriate in this scenario where each animal is assigned to one cage and each cage contains only one animal.

The code you provided, would set up a one-to-one association between the cage and animal models in Sequelize.

db.cage.hasOne(db.animal) establishes a one-to-one relationship between the cage and animal models, where a cage has one animal, and db.animal.belongsTo(db.cage) establishes the inverse relationship, where an animal belongs to one cage. These two lines of code are necessary to set up the proper relationship between the two models.

You are correct that using db.cage.hasMany(db.animal) would not work in this case as it would indicate a one-to-many relationship, where a cage can have multiple animals.

And you don't have to add the foreign key reference manually because Sequelize will automatically add the foreign key in the animal table to reference the cage table.

Hope this helps!

Cheers!

  • Related