Exploring Sequelize Schema and Model Usage

Exploring Sequelize Schema and Model Usage

Sequelize, a promise-based Node.js ORM for Postgres, MySQL, MariaDB, SQLite, and Microsoft SQL Server, offers an efficient way to manage and interact with databases. It abstracts complex SQL queries, provides easy-to-use methods for CRUD operations, and much more. This article delves into the usage of schemas and models in Sequelize, exemplified through a practical scenario involving email data management.

Defining Models

In Sequelize, a model represents a table in the database. Models are defined by specifying their name and attributes, each attribute representing a column in the table. Consider the following example, which illustrates the model definition process:

const Sequelize = require('sequelize');
const sequelize = new Sequelize('database', 'username', 'password', {
   
  dialect: 'yourDialect',
});

const Mail = sequelize.define('Mail', {
   
  subjectDailyReport: {
   
    type: Sequelize.STRING,
    allowNull: false,
  },
  sendTime: {
   
    type: Sequelize.DATE,
    allowNull: false,
  },
  // Additional attributes can be defined here
});

This code snippet outlines the creation of a Mail model with two fields: subjectDailyReport and sendTime. The define method takes three arguments: the model name, the model attributes, and optional model options.

CRUD Operations

Sequelize models come with a variety of methods to perform CRUD operations. These methods offer a high level of abstraction over direct SQL queries, making database interactions more intuitive and less error-prone.

Create

To add a new record to the database, the create method is used. This method inserts a new row into the corresponding table:

const createpreSutBooking = async (subjectDailyReport, sendTime) => {
   
  try {
   
    const mail = await Mail.create({
    subjectDailyReport, sendTime });
    return mail;
  } catch (error) {
   
    throw error;
  }
};
Read

Retrieving data from the database can be achieved using methods like findOne for fetching a single record and findAll for multiple records. The following example demonstrates fetching the most recently created Mail record:

const getpreSutBooking = async () => {
   
  try {
   
    const mail = await Mail.findOne({
    order: [['createdAt', 'ASC']] });
    return mail;
  } catch (error) {
   
    throw error;
  }
};
Update

Updating existing records is straightforward with the update method. This method applies updates to the record that matches the provided criteria:

const savepreSutBooking = async (data) => {
   
  try {
   
    const {
    subjectDailyReport, sendTime } = data;
    const mail = await Mail.findOne({
    order: [['createdAt', 'ASC']] });
    if (mail) {
   
      const updatedRecord = await mail.update({
    subjectDailyReport, sendTime });
      return updatedRecord;
    } else {
   
      return '没有找到匹配的记录'; // 'No matching record found'
    }
  } catch (error) {
   
    throw error;
  }
};
Delete

To remove records from the database, the destroy method is used. It deletes records that match the specified criteria:

const deletepreSutBooking = async () => {
   
  try {
   
    await Mail.destroy({
    where: {
   } });
  } catch (error) {
   
    throw error;
  }
};

Additionally, for completely clearing a table, the truncate option can be used with the destroy method to remove all records and reset any auto-increment values.

Conclusion

Sequelize offers a robust set of features for database schema and model management, significantly simplifying the process of performing CRUD operations. By abstracting direct SQL queries, Sequelize allows for more maintainable and readable code, making it an excellent choice for web application development involving relational databases.

相关推荐

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-02-05 11:06:01       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-02-05 11:06:01       106 阅读
  3. 在Django里面运行非项目文件

    2024-02-05 11:06:01       87 阅读
  4. Python语言-面向对象

    2024-02-05 11:06:01       96 阅读

热门阅读

  1. 疑惑问题总结

    2024-02-05 11:06:01       54 阅读
  2. 支付交易——支付原理

    2024-02-05 11:06:01       47 阅读
  3. Xor 特殊情况_题解

    2024-02-05 11:06:01       48 阅读
  4. MySQL数据存储

    2024-02-05 11:06:01       53 阅读
  5. 什么是API

    2024-02-05 11:06:01       56 阅读
  6. Springboot中的起步依赖和自动装配

    2024-02-05 11:06:01       54 阅读
  7. 机器学习7-K-近邻算法(K-NN)

    2024-02-05 11:06:01       51 阅读
  8. Python 随机模块(Random Module)

    2024-02-05 11:06:01       48 阅读
  9. easyexcle 导出csv

    2024-02-05 11:06:01       47 阅读
  10. Transformer的PyTorch实现之若干问题探讨(一)

    2024-02-05 11:06:01       59 阅读