DEV Community

Discussion on: Getting Started with Sequelize and Postgres

Collapse
 
nedsoft profile image
Chinedu Orie • Edited

Hi Jakub, I deliberately did not add the foreign key constraints in the migrations. Adding the foreign key constraints in the migrations makes integration with the models very rigid and most times it can be a pain.

From my experience enforcing foreign key constraints in the migrations is good if only at the time of writing the migration you have completely figured out all the models and the relationships that exist between them. This is because foreign key constraints demand that the parent table's migration must precede the child table. In deleting, you cannot delete a parent table if it has a child (this is a good feature btw).

Of course, enforcing the FK constraint ensures data integrity but the opportunity cost most time for me is higher.

So what I do is to define the model relationship in the models, this will do the same job of associating the tables as defining the FK constraint in the migrations in addition to ensuring flexibility in interacting with the tables/models.

Looking at the code used for the article, say

//database/models/user.js

module.exports = (sequelize, DataTypes) => {
  const User = sequelize.define('User', {
    name: DataTypes.STRING,
    email: DataTypes.STRING
  }, {});
  User.associate = function(models) {
    // associations can be defined here
    User.hasMany(models.Post, {
      foreignKey: 'userId',
      as: 'posts',
      onDelete: 'CASCADE',
    });

    User.hasMany(models.Comment, {
      foreignKey: 'userId',
      as: 'comments',
      onDelete: 'CASCADE',
    });
  };
  return User;
};

Enter fullscreen mode Exit fullscreen mode

You can see how the relationships were defined.
Like to the repo here

The pattern used here is strictly opinionated.

Let me know if that helped.

Collapse
 
jakub41 profile image
Jakub

Hi thanks for the help :)

However, the issue is that in this way on DB I have manually to make the foreign key to have the relationship as I have to make 2 tables related.
Here what I'm trying to do:
github.com/Jakub41/School-API-PSQL
I have an exercise to make projects related to Students.
A student has many projects but a project has one student.
So I have to make it on my own on the DB then this?
Thanks

Thread Thread
 
nedsoft profile image
Chinedu Orie • Edited

The explanation I gave above answered this question already. I can only repeat the same thing.
You correctly defined the relationship between student and project.
If you remove the constraints in the migrations, you'll still get the expected results in terms of the relationship

For example

student_id: {
                foreignKey: true,
                type: Sequelize.UUID,
                defaultValue: Sequelize.UUIDV4,
                allowNull: false
            },

could be

student_id: {
                type: Sequelize.UUID,
                defaultValue: Sequelize.UUIDV4,
                allowNull: false
            },

also check sequelize docs for how to add Fk constraint, the snippet below was copied from the docs

module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.createTable('Person', {
      name: Sequelize.STRING,
      isBetaMember: {
        type: Sequelize.BOOLEAN,
        defaultValue: false,
        allowNull: false
      },
      userId: {
        type: Sequelize.INTEGER,
        references: {
          model: {
            tableName: 'users',
            schema: 'schema'
          }
          key: 'id'
        },
        allowNull: false
      },
    });
  },

  down: (queryInterface, Sequelize) => {
    return queryInterface.dropTable('Person');
  }
}

Thread Thread
 
jakub41 profile image
Jakub

Thanks :)

I have 2 questions:

1) "schema" what is that? I should live schema or I need to define something? Is not clear from docs actually what that means

2) There 2 ways of doing this kind of stuff no async/async, what method is better or how to choose which one to use? It is not really clear to me from the docs.

Thanks for helping :D

Thread Thread
 
nedsoft profile image
Chinedu Orie

Schema is the entire structure of the database, including the tables and the relationships that exist between them.

If you are referring to something somewhere, you can share the link to the reference, that way it'll be easier for me to relate with.

Thread Thread
 
jakub41 profile image
Jakub

I see thanks so in that field I have to put the name of my database but I also need to have a schema defined of my dB in the project?
Sorry for many questions but I'm learning 😁

Another question when you create at or update at and want this is generated by server do I have to add default values NOW? And for Uuid same? In sense UUIDV4?
I'm asking because seems is not generating that when I input records to the dB is giving me Null errors but should be autogenerated fields. Thanks again 😁