【发布时间】:2018-08-15 14:15:00
【问题描述】:
这是我的实体:
@Entity()
export class Game extends BaseEntity {
@PrimaryGeneratedColumn({
name: "id",
})
private _id: number;
@Column({
name: "name",
type: "varchar",
nullable: false,
})
private _name: string;
get id(): number {
return this._id;
}
set id(id: number) {
this._id = id;
}
get name(): string {
return this._name;
}
set name(name: string) {
this._name = name;
}
}
当我尝试创建一个新游戏时,我想使用Repository API。
所以我要做的是:
import { getRepository } from "typeorm";
import { Game } from "../entities/game.entity";
import { InsertGameConfig } from "../interfaces/entities/game";
public async insert(config: InsertGameConfig) {
return await getRepository(Game).create(config).save();
}
并像这样调用插入函数:
await insert({
name: "test",
});
但是当我检查 mysql 查询日志时,我发现:
INSERT INTO `game`(`id`, `name`) VALUES (DEFAULT, DEFAULT)
但是,如果我创建实例并像这样设置每个值:
const game = new Game();
game.name = config.name;
return await game.save();
然后它就可以正常工作了,所以:
INSERT INTO `game`(`id`, `name`) VALUES (DEFAULT, "test")
来自 TypeOrm 文档:
create - 创建一个新的用户实例。可选地接受带有用户属性的对象字面量,该对象字面量将被写入新创建的用户对象中。
const user = repository.create(); // same as const user = new User();
const user = repository.create({
id: 1,
firstName: "Timber",
lastName: "Saw"
}); // same as const user = new User(); user.firstName = "Timber"; user.lastName = "Saw";
注意
我尝试将类的属性设置为 public,然后 create 可以正常工作,但是当它们是私有的并且我使用 getter/setter 时,它就不起作用了。
【问题讨论】:
标签: mysql typescript typeorm