Convert SQL FOREIGN KEY to Sequelize belongsTo Association

Learn how SQL FOREIGN KEY constraints and inline REFERENCES clauses are converted to Sequelize belongsTo associations with foreignKey and targetKey options.

Associations

Detailed Explanation

Foreign Keys and belongsTo in Sequelize

When the converter encounters a FOREIGN KEY constraint or an inline REFERENCES clause, it generates a Sequelize belongsTo association declaration. This is the most common relationship pattern: a child table references a parent table.

Inline REFERENCES Syntax

CREATE TABLE comments (
  id SERIAL PRIMARY KEY,
  body TEXT NOT NULL,
  post_id INTEGER NOT NULL REFERENCES posts(id),
  user_id INTEGER NOT NULL REFERENCES users(id)
);

The converter generates:

  1. A references property on the column definition
  2. A belongsTo association comment
post_id: {
  type: DataTypes.INTEGER,
  allowNull: false,
  references: { model: 'posts', key: 'id' },
},
// Comment.belongsTo(Post, { foreignKey: 'post_id', targetKey: 'id' });

Table-Level FOREIGN KEY

The table-level syntax is also supported:

CREATE TABLE order_items (
  id SERIAL PRIMARY KEY,
  order_id INTEGER NOT NULL,
  product_id INTEGER NOT NULL,
  FOREIGN KEY (order_id) REFERENCES orders(id),
  FOREIGN KEY (product_id) REFERENCES products(id)
);

CONSTRAINT Named Foreign Keys

Named constraints are parsed the same way:

CONSTRAINT fk_order FOREIGN KEY (order_id) REFERENCES orders(id)

Association Setup Pattern

In a typical Sequelize project, associations are set up in a separate file or an associate static method:

// In models/index.js or a dedicated associations file
Comment.belongsTo(Post, { foreignKey: 'post_id', targetKey: 'id' });
Comment.belongsTo(User, { foreignKey: 'user_id', targetKey: 'id' });

The converter generates these as comments so you can copy them into your association setup. The references property on the column itself tells Sequelize to create the foreign key constraint at the database level when using sync() or migrations.

Use Case

You are building a comment system where comments belong to both a post and a user. Converting the SQL schema correctly identifies both foreign keys and generates the appropriate belongsTo associations.

Try It — SQL to Sequelize Model

Open full tool