Skip to content

创建

创建记录

使用 insert() 方法创建单条记录:

ts
import { Table, Column, PrimaryKey, getORM } from '@ibestservices/ibest-orm';

@Table()
class User {
  @PrimaryKey()
  id?: number;

  @Column()
  name?: string;

  @Column()
  age?: number;
}

const orm = getORM();

// 创建实体并插入
const user = new User();
user.name = '张三';
user.age = 18;

const id = orm.insert(user);  // 返回插入的 ID
console.log('插入成功,ID:', id);

批量创建

使用数组批量插入多条记录:

ts
const users = [
  { name: '张三', age: 18 },
  { name: '李四', age: 20 },
  { name: '王五', age: 22 }
];

// 批量插入
users.forEach(data => {
  const user = new User();
  user.name = data.name;
  user.age = data.age;
  orm.insert(user);
});

智能保存

使用 save() 方法智能保存:有 ID 则更新,无 ID 则插入。

ts
const user = new User();
user.name = '张三';
user.age = 18;

// 首次保存(插入)
orm.save(user);  // user.id 会被自动赋值

// 修改后再次保存(更新)
user.age = 20;
orm.save(user);  // 根据 id 更新

自动时间戳

使用 @CreatedAt@UpdatedAt 装饰器自动管理时间:

ts
import { Table, Column, PrimaryKey, CreatedAt, UpdatedAt } from '@ibestservices/ibest-orm';

@Table()
class Article {
  @PrimaryKey()
  id?: number;

  @Column()
  title?: string;

  @CreatedAt()
  createdAt?: string;  // 插入时自动填充

  @UpdatedAt()
  updatedAt?: string;  // 插入和更新时自动填充
}

const article = new Article();
article.title = '文章标题';
orm.insert(article);
// createdAt 和 updatedAt 会自动设置为当前时间

配置时间格式

可以全局配置时间格式:

ts
import { setTimeFormat } from '@ibestservices/ibest-orm';

// 支持的格式:'datetime' | 'date' | 'time' | 'timestamp' | 'iso'
setTimeFormat('datetime');  // 默认:2024-01-01 12:00:00
setTimeFormat('iso');       // ISO 格式:2024-01-01T12:00:00.000Z
setTimeFormat('timestamp'); // 时间戳:1704067200000

数据验证

插入前可以进行数据验证:

ts
import { Required, Length, Range, validate } from '@ibestservices/ibest-orm';

@Table()
class User {
  @PrimaryKey()
  id?: number;

  @Required()
  @Length(2, 20)
  @Column()
  name?: string;

  @Range(0, 150)
  @Column()
  age?: number;
}

const user = new User();
user.name = 'A';  // 太短,验证会失败
user.age = 200;   // 超出范围

const result = validate(user);
if (!result.valid) {
  console.log('验证失败:', result.errors);
  // 不插入
} else {
  orm.insert(user);
}

事务中创建

在事务中创建多条记录,确保数据一致性:

ts
orm.transaction(() => {
  const user1 = new User();
  user1.name = '用户1';
  orm.insert(user1);

  const user2 = new User();
  user2.name = '用户2';
  orm.insert(user2);

  // 如果任何操作失败,所有操作都会回滚
});