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.

你可能感兴趣的:(English,mysql,node)