1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

typeormで値をnullに変更する実装バリエーション

Posted at

typeormで一度設定した状態からnullに戻す実装を何パターンか調べたので備忘録として残します

typeorm ^0.2.28
typescript ^3.9.5

update 実装

updateでundefinedを設定すると、自動的にnullに更新されます

@Column({ nullable: true })
fugaId?: number
import { getManager } from "typeorm"
const repo = getManager().getRepository(Hoge)
await repo.update({ id: 1 }, {fugaId: undefined})

// fugaId: null

save 実装で、fugaId = null にする

@Column({ nullable: true, type: "int" })
fugaId?: number | null
import { getManager } from "typeorm"

let target = await repo.findOne(1)
const repo = getManager().getRepository(Hoge)
target!.salesPicUserId = null
await repo.save(target!)

// fugaId: null

save 実装で、fugaId = undefined なら null にするように変換をかけて保存

@Column({
  nullable: true, transformer: {
    to: (value: number) => {
      if (value === undefined) {
        return null
      }
    },
    from: (value: number) => value
  },
  type: "int"
})
fugaId?: number | null
import { getManager } from "typeorm"

let target = await repo.findOne(1)
const repo = getManager().getRepository(Hoge)
target!.salesPicUserId = null
await repo.save(target!)

// fugaId: null

他にもあれば教えてください!

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?