TypeORM:添加具有数组数据类型的列
使用 TypeORM 时,可以使用数组数据类型定义列。
如果要添加存储数字数组的列,可以这样定义:
@Column('integer', {
array: true, // this is supported by postgreSQL only
nullable: true,
})
sizes: number[];
如果您需要一个存储字符串数组的列,您可以像这样定义它:
@Column('simple-array', { nullable: true })
colors: string[];
请务必注意,您的数组的任何元素中都不得有任何逗号。
下面的示例创建了一个名为products的表,其中一些列的类型是数组:
// Product entity
import {
Entity,
PrimaryGeneratedColumn,
Column,
CreateDateColumn,
} from 'typeorm';
@Entity({name: 'products'})
export class Product {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
// array of numbers
@Column('integer', {
array: true, // this is supported by postgres only
nullable: true,
})
sizes: number[];
// array of strings
@Column('simple-array', { nullable: true })
colors: string[];
@Column({ type: 'simple-array', nullable: true })
materials: string[];
@CreateDateColumn()
createdAt: Date;
}
以下是我们保存新记录的方法:
const productRepository = dataSource.getRepository(Product);
const product = new Product();
product.name = 'KindaCode.com';
product.sizes = [1, 2, 3];
product.colors = ['red', 'blue', 'green'];
product.materials = ['wood', 'metal', 'plastic'];
await productRepository.save(product);
查看已添加到数据库的数据时,您会看到如下内容:
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。