我正在尝试使用typeorm实现级联插入.子表条目包括对父表ID字段的外键引用.
看来typeorm并未从父行中捕获自动增量id并将其提供给子插入.
这是父实体:
import ...
@Entity("parent")
export class Parent {
@PrimaryGeneratedColumn()
id: number;
@OneToOne(type => Account, accountId => accountId.provider)
@JoinColumn({name: "account_id"})
accountId: Account;
@Column("varchar", {
name: "name",
nullable: false,
length: 255,
})
name: string;
@OneToMany(type => Child, Children => Children.parentId, {
cascadeInsert: true,
cascadeUpdate: true
})
Children: Child[];
}
子实体:
import ...
@Entity("child")
export class Child{
@PrimaryGeneratedColumn()
id: number;
@ManyToOne(type => Parent, parentId => parentId.children)
@JoinColumn({name: "parent_id"})
parentId: Parent;
@Column("varchar", {
name: "number",
nullable: true,
length: 45,
})
number: string;
}
控制台日志显示所生成的sql不包含外键列,从而产生明显的错误ER_NO_DEFAULT_FOR_FIELD:字段“ parent_id”没有默认值
info: executing query: START TRANSACTION
info: executing query: INSERT INTO parent(name, account_id) VALUES (?,?) -- PARAMETERS: ["Name","id"]
info: executing query: INSERT INTO child(number) VALUES (?) -- PARAMETERS: ["12345678"]
info: query failed: INSERT INTO child(number) VALUES (?) -- PARAMETERS: ["12345678"]
info: error: { Error: ER_NO_DEFAULT_FOR_FIELD: Field 'parent_id' doesn't have a default value
是否可以通过某种方式指示typeorm捕获LAST_INSERT_ID()或以其他方式填充子行上的foregin键id字段?
解决方法:
如果ID不是自动生成的,而是在保存实体之前分配的,则该ID有效.
使用uuid作为主键.
import ...
@Entity("parent")
export class Parent {
@PrimaryColumn()
id: string;
@OneToOne(type => Account, accountId => accountId.provider)
@JoinColumn({name: "account_id"})
accountId: Account;
@Column("varchar", {
name: "name",
nullable: false,
length: 255,
})
name: string;
@OneToMany(type => Child, Children => Children.parentId, {
cascadeInsert: true,
cascadeUpdate: true
})
Children: Child[];
}
和创建实体时.
const parent: Parent = new Parent();
parent.id = "896b677f-fb14-11e0-b14d-d11ca798dbac"; // your uuid goes here
不幸的是,您也不能使用@PrimaryGeneratedColumn(“ uuid”).
有很多库可以在JS中生成uuid.
uuid-js的示例-https://github.com/pnegri/uuid-js
const parent: Parent = new Parent();
parent.id = UUID.create(4).toString();
我认为这更像是一种解决方法,而不是问题的解决方案.但是我找不到一种让TypeORM在级联孩子时考虑生成的ID的方法.