Generate Sequelize hasMany from SQL Foreign Key Relationships

Understand how the converter infers hasMany reverse associations from SQL FOREIGN KEY constraints and generates commented hints for both sides of the relationship.

Associations

Detailed Explanation

hasMany: The Reverse Side of belongsTo

Every belongsTo relationship has a corresponding hasMany (or hasOne) on the other side. When the converter detects a foreign key from table B to table A, it generates both:

  1. B.belongsTo(A) — on the child model
  2. A.hasMany(B) — as a commented hint in the reverse associations section

Example: Users and Posts

CREATE TABLE users (
  id SERIAL PRIMARY KEY,
  name VARCHAR(255) NOT NULL
);

CREATE TABLE posts (
  id SERIAL PRIMARY KEY,
  title VARCHAR(255) NOT NULL,
  author_id INTEGER NOT NULL REFERENCES users(id)
);

The converter produces:

// On the Post model:
// Post.belongsTo(User, { foreignKey: 'author_id', targetKey: 'id' });

// In the reverse associations section:
// User.hasMany(Post, { foreignKey: 'author_id' });

Why Comments Instead of Executable Code?

The converter generates hasMany as comments because:

  1. Circular dependencies: In a modular project, model files import each other. Placing both association sides in the model files creates circular imports.
  2. Association setup pattern: Best practice is to call associations in a central models/index.js or a dedicated associations.js file after all models are loaded.
  3. Flexibility: You may want hasOne instead of hasMany, or you may want to add as aliases, onDelete, and onUpdate options.

Setting Up Both Sides

// models/associations.js
const { User, Post, Comment } = require('./');

User.hasMany(Post, { foreignKey: 'author_id', as: 'posts' });
Post.belongsTo(User, { foreignKey: 'author_id', as: 'author' });

Post.hasMany(Comment, { foreignKey: 'post_id', as: 'comments' });
Comment.belongsTo(Post, { foreignKey: 'post_id' });

Eager Loading

Once both sides are set up, you can use Sequelize's include option for eager loading:

const user = await User.findByPk(1, {
  include: [{ model: Post, as: 'posts' }]
});

Use Case

You have a multi-table schema with several one-to-many relationships. The converter identifies all foreign keys and provides hasMany hints so you can quickly set up both sides of every relationship in your Sequelize association file.

Try It — SQL to Sequelize Model

Open full tool