【发布时间】:2018-08-29 01:14:22
【问题描述】:
我不确定这是否是一个错误,或者我做错了什么,但我尝试了很多方法来让它工作,但我做不到。希望大家帮忙。
基本上我有一对一的关系,我需要lazyLoad。关系树在我的项目中有点大,我无法在没有承诺的情况下加载它。
我面临的问题是,当我保存一个孩子时,父更新生成的sql缺少更新字段:UPDATE `a` SET WHERE `id` = 1
当我不使用lazyLoading(Promises)时,这可以完美运行。
我使用生成的代码工具设置了一个简单的示例。
实体 A
@Entity()
export class A {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@OneToOne(
(type: any) => B,
async (o: B) => await o.a
)
@JoinColumn()
public b: Promise<B>;
}
实体 B
@Entity()
export class B {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@OneToOne(
(type: any) => A,
async (o: A) => await o.b)
a: Promise<A>;
}
main.ts
createConnection().then(async connection => {
const aRepo = getRepository(A);
const bRepo = getRepository(B);
console.log("Inserting a new user into the database...");
const a = new A();
a.name = "something";
const aCreated = aRepo.create(a);
await aRepo.save(aCreated);
const as = await aRepo.find();
console.log("Loaded A: ", as);
const b = new B();
b.name = "something";
const bCreated = bRepo.create(b);
bCreated.a = Promise.resolve(as[0]);
await bRepo.save(bCreated);
const as2 = await aRepo.find();
console.log("Loaded A: ", as2);
}).catch(error => console.log(error));
输出
Inserting a new user into the database...
query: SELECT `b`.`id` AS `b_id`, `b`.`name` AS `b_name` FROM `b` `b` INNER JOIN `a` `A` ON `A`.`bId` = `b`.`id` WHERE `A`.`id` IN (?) -- PARAMETERS: [[null]]
query: START TRANSACTION
query: INSERT INTO `a`(`id`, `name`, `bId`) VALUES (DEFAULT, ?, DEFAULT) -- PARAMETERS: ["something"]
query: UPDATE `a` SET WHERE `id` = ? -- PARAMETERS: [1]
query failed: UPDATE `a` SET WHERE `id` = ? -- PARAMETERS: [1]
如果我从实体中删除承诺,一切正常:
实体 A
...
@OneToOne(
(type: any) => B,
(o: B) => o.a
)
@JoinColumn()
public b: B;
}
实体 B
...
@OneToOne(
(type: any) => A,
(o: A) => o.b)
a: A;
}
main.ts
createConnection().then(async connection => {
...
const bCreated = bRepo.create(b);
bCreated.a = as[0];
await bRepo.save(bCreated);
...
输出
query: INSERT INTO `b`(`id`, `name`) VALUES (DEFAULT, ?) -- PARAMETERS: ["something"]
query: UPDATE `a` SET `bId` = ? WHERE `id` = ? -- PARAMETERS: [1,1]
query: COMMIT
query: SELECT `A`.`id` AS `A_id`, `A`.`name` AS `A_name`, `A`.`bId` AS `A_bId` FROM `a` `A`
我还创建了一个 git 项目来说明这一点并便于测试。
1) 使用承诺(不工作)https://github.com/cuzzea/bug-typeorm/tree/promise-issue
2) 没有延迟加载(工作)https://github.com/cuzzea/bug-typeorm/tree/no-promise-no-issue
【问题讨论】:
标签: typescript lazy-loading one-to-one typeorm