前提
- node 10.x
- typescript 3.5.3
- typeorm 0.2.18
- mysql 5.7
実現したいこと
typeormで
OneToOne
or OneToMany
のカラムを nullable: false
にする。
その上で cascade Insert, Update
したい。
発生している問題・エラーメッセージ
QueryFailedError: ER_BAD_NULL_ERROR: Column 'device_id' cannot be null
該当のソースコード
index.ts
typescript
1// index.ts 2 3import {getRepository} from 'typeorm'; 4import {Parent} from ''; 5import {Child} from ''; 6 7const testCreate = async () => { 8 const parentRepository = getRepository(Parent); 9 10 const parent = new Parent(); 11 const child = new Child(); 12 13 parent.children = [child]; 14 15 await parentRepository.save(parent); 16} 17
child.ts
typescript
1// child.ts 2 3import { 4 Entity, 5 PrimaryGeneratedColumn, 6 Column, 7 BaseEntity, 8 ManyToOne, JoinColumn, CreateDateColumn, UpdateDateColumn } from 'typeorm'; 9import { PrimaryGeneratedColumnUUIDOptions } from 'typeorm/decorator/options/PrimaryGeneratedColumnUUIDOptions'; 10import { Parent } from './parent'; 11 12@Entity('CHILD') 13export class Child extends BaseEntity { 14 @PrimaryGeneratedColumn('uuid') 15 public readonly id?: PrimaryGeneratedColumnUUIDOptions; 16 17 @ManyToOne( 18 (type) => Parent, 19 (parent) => parent.children, 20 { nullable: false }, 21 ) 22 @JoinColumn({ name: 'parent_id' }) 23 public parent!: Parent; 24 25 @CreateDateColumn({ name: 'created_at', type: 'timestamp' }) 26 public readonly createdAt?: Date; 27 28 @UpdateDateColumn({ name: 'updated_at', type: 'timestamp' }) 29 public readonly updatedAt?: Date; 30 31 constructor( 32 fields: { 33 parent?: Parent, 34 }, 35 ) { 36 super(); 37 Object.assign(this, fields); 38 } 39 40}
parent.ts
typescript
1import { 2 Entity, 3 PrimaryGeneratedColumn, 4 Column, 5 BaseEntity, 6 OneToMany, CreateDateColumn, UpdateDateColumn } from 'typeorm'; 7import { child } from './child'; 8 9@Entity('PARENT') 10export class Parent extends BaseEntity { 11 @PrimaryGeneratedColumn({ type: 'bigint' }) 12 public readonly id?: number; 13 14 @CreateDateColumn({ name: 'created_at', type: 'timestamp' }) 15 public readonly createdAt?: Date; 16 17 @UpdateDateColumn({ name: 'updated_at', type: 'timestamp' }) 18 public readonly updatedAt?: Date; 19 20 @OneToMany( 21 (type) => Child, 22 (child) => child.parent, 23 { cascade: true }, 24 ) 25 public children?: Child[]; 26 27}
試したこと
childの { nullable: false }
を外すと正常に動作する。
あなたの回答
tips
プレビュー