Creating Sequelize ORM Model and Column

Sequelize ORM Model ve Column Oluşturma

Creating Sequelize ORM Model and Column

Using an ORM (Object Relational Mapping) for database management in modern Node.js applications offers great convenience. Sequelize ORM is one of the most popular choices, thanks to its flexible structure and broad community support. In this article, you will learn the steps to create a model and columns using Sequelize ORM, complete with technical details and code examples.

Creating a Model in Sequelize

The Model concept refers to JavaScript classes that represent database tables. To create a model with Sequelize ORM, you must first add the sequelize package and the appropriate database driver to your project:

npm install sequelize sqlite3

After installation, you can create the sequelize object and define your model as follows:

const {{ Sequelize, DataTypes }} = require('sequelize');
const sequelize = new Sequelize('sqlite::memory:');

const User = sequelize.define('User', {{
  // Columns will be defined here
}});

Defining Columns in Sequelize ORM

The columns in each model define the structure of the table. For example, to add username and email fields to a user table:

const User = sequelize.define('User', {{
  username: {{
    type: DataTypes.STRING,
    allowNull: false
  }},
  email: {{
    type: DataTypes.STRING,
    allowNull: false,
    unique: true
  }}
}});

In this example, properties such as the types, non-nullability (allowNull), and uniqueness (unique) of the username and email columns are configured. Sequelize ORM is quite flexible in this regard when it comes to creating columns.

Synchronizing the Model

To create the table in your database, you can use the following code:

sequelize.sync()
  .then(() => {{
    console.log('User table created.');
  }});

Conclusion: Powerful Data Modeling with Sequelize ORM

With Sequelize ORM model and column creation, you can easily shape the database layer of your projects and build a strong, maintainable structure in your code. Sequelize offers you many advantages, such as migration management, defining relational structures, and type safety. With proper modeling, your database operations will be both fast and secure.