📅  最后修改于: 2023-12-03 14:40:38.081000             🧑  作者: Mango
Sequelize is a Node.js ORM (Object-Relational Mapping) for MySQL, PostgreSQL, SQLite, and MSSQL. It provides a way to interact with databases in an object-oriented manner, using JavaScript syntax.
In this article, we'll take a look at how to use DataTypes and Time in Sequelize.
Sequelize provides a set of DataTypes that can be used to define your model's columns. Some of the most commonly used DataTypes are:
Here's an example of how to define a model's columns using DataTypes:
const { DataTypes } = require('sequelize');
const sequelize = new Sequelize('database', 'username', 'password', {
dialect: 'mysql'
});
const User = sequelize.define('User', {
name: {
type: DataTypes.STRING,
allowNull: false
},
email: {
type: DataTypes.STRING,
allowNull: false
},
age: {
type: DataTypes.INTEGER
}
});
In the above example, we define a "User" model with three columns: "name", "email", and "age". The "name" and "email" columns are of type STRING and are required ("allowNull: false"). The "age" column is of type INTEGER and is optional.
Sequelize supports various time-related DataTypes, such as DATE, TIME and DATEONLY. These data types allow storing time-related data into the database.
Here's an example of how to define time-related columns in Sequelize:
const { DataTypes } = require('sequelize');
const sequelize = new Sequelize('database', 'username', 'password', {
dialect: 'mysql'
});
const BlogPost = sequelize.define('BlogPost', {
title: {
type: DataTypes.STRING,
allowNull: false
},
content: {
type: DataTypes.TEXT,
allowNull: false
},
published_at: {
type: DataTypes.DATE
},
last_updated_at: {
type: DataTypes.DATE
}
});
In the above example, we define a "BlogPost" model with four columns: "title", "content", "published_at", and "last_updated_at". The "published_at" and "last_updated_at" columns are of type DATE, which allows storing both date and time.
DataTypes and Time are essential components of Sequelize. They enable us to define columns in our models and store time-related data into our databases. In this article, we explained how to use these features in Sequelize.
References: