我有以下要保存的实体:
@Entity('approvals')
export class Approval {
@PrimaryGeneratedColumn()
id: string;
@ManyToOne(type => Task, task => task.approvals, {nullable: false, onDelete: 'CASCADE', lazy: true})
task: Promise<Task> | Task;
@ManyToOne(type => User, user => user.approvals, {nullable: false, onDelete: 'CASCADE', lazy: true})
user: Promise<User> | User;
@Column({ type: 'enum', enum: ApprovalState, default: ApprovalState.None })
state: ApprovalState;
constructor(partialApproval: Partial<Approval>) {
Object.assign(this, partialApproval);
}
}
如果我想保存一个如下所示的实体(调试时复制):
[
{
"task": {
"id": "2",
"name": "task1",
"type": "type1",
"neededTimeSeconds": 0,
"factor": 1,
"userId": "1",
"periodStart": "2019-01-01",
"periodEnd": "2019-01-31",
"done": true,
"__user__": {
"id": "1",
"username": "user1",
"password": "$2b$10$SBPIVm9p8L4YkpiUVJ.mpedIgWi5Je6MuWTM7IvgMdyhr27JYM0OG",
"credits": 0,
"gravatarHash": null
},
"__has_user__": true
},
"user": {
"id": "2",
"username": "shouldHaveApprovalUser1",
"password": "password1",
"credits": 0,
"gravatarHash": null
}
},
{
"task": {
"id": "2",
"name": "task1",
"type": "type1",
"neededTimeSeconds": 0,
"factor": 1,
"userId": "1",
"periodStart": "2019-01-01",
"periodEnd": "2019-01-31",
"done": true,
"__user__": {
"id": "1",
"username": "user1",
"password": "$2b$10$SBPIVm9p8L4YkpiUVJ.mpedIgWi5Je6MuWTM7IvgMdyhr27JYM0OG",
"credits": 0,
"gravatarHash": null
},
"__has_user__": true
},
"user": {
"id": "3",
"username": "shouldHaveApprovalUser2",
"password": "password1",
"credits": 0,
"gravatarHash": null
}
}
]
然后用上面的数组调用repository.save()
,得到:
null value in column "taskId" violates not-null constraint
虽然这里明确地把id
定义在每个task
中。
这是Task
实体类:
@Entity('tasks')
export class Task {
@PrimaryGeneratedColumn({ type: 'bigint' })
id: string;
@Column({ length: 30 })
name: string;
@Column({ default: 'help' })
type: string;
@Column({ name: 'needed_time', type: 'int', nullable: true })
neededTimeSeconds: number;
@Column({ type: 'int', default: 1 })
factor: number;
@ManyToOne(type => User, { nullable: true, lazy: true })
@JoinColumn({ name: 'user_id' })
user: Promise<User>;
@Column({ name: 'user_id' })
@RelationId((task: Task) => task.user)
userId: string;
@Column({ name: 'period_start', type: 'date', default: new Date() })
periodStart: string;
@Column({ name: 'period_end', type: 'date', default: new Date() })
periodEnd: string;
@Column({ type: 'boolean', default: false })
done: boolean;
@OneToMany(type => Approval, approval => approval.task, { nullable: true, lazy: true })
approvals: Promise<Approval[]>;
@OneToMany(type => TaskMessage, taskMessage => taskMessage.task, { cascade: ['remove'], lazy: true })
messages: Promise<TaskMessage[]>;
constructor(partialTask: Partial<Task>) {
Object.assign(this, partialTask);
}
}
谁能告诉我为什么不分配/保存关系task
?
2条答案
按热度按时间hlswsv351#
我认为您遗漏了关系选项的
cascade: true
,这应该设置在关系的松散端(OneToMany)-检查示例5lhxktic2#
github.com/typeorm/typeorm/issues/2129
储存延迟载入的实体时发生问题。更多信息请参阅链接