乐闻世界logo
搜索文章和话题

How to create entity column with TIME type in TypeORM

1个答案

1

Creating TIME type entity columns in TypeORM primarily involves defining a property in your entity class with a specific data type decorator. The following provides specific steps and examples demonstrating how to create a TIME type column within an entity:

Step 1: Define the Entity

First, you need to define an entity class. An entity class represents a table in the database, and each property in the class maps to a column in the table.

typescript
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm'; @Entity() export class Schedule { @PrimaryGeneratedColumn() id: number; @Column({ type: 'time' }) startTime: string; }

Detailed Explanation

  • The @Entity() decorator marks the class as a database table.
  • The @PrimaryGeneratedColumn() decorator declares a primary key column, whose value is auto-generated.
  • The @Column({ type: 'time' }) decorator defines a column of type time. Here, the type is set to 'time', meaning the database column will store time values.

Example Usage

Suppose you want to store a start time for the day, such as '09:00:00'. You can simply assign this time as a string to the startTime property.

typescript
const newSchedule = new Schedule(); newSchedule.startTime = '09:00:00';

In this example, the startTime property of the newSchedule object is set to '09:00:00' string. When saving this object to the database, TypeORM will store the time string in the corresponding TIME type column.

Important Notes

  • Ensure your database supports the TIME type. Most modern relational databases like MySQL, PostgreSQL, and SQL Server support this type.
  • When interacting with the database using Node.js, note that TIME type data is typically converted to string format.

By following these steps and examples, you can effectively create and manage TIME type data columns in TypeORM. This approach is particularly useful for handling time-only data (without dates), such as business hours or opening hours.

2024年6月29日 12:07 回复

你的答案