#author("2024-03-30T01:21:10+00:00","default:wikiadmin","wikiadmin")
#author("2024-03-30T01:21:30+00:00","default:wikiadmin","wikiadmin")
-TypeScriptのOR Mapper

*チート集 [#t0bdbe1d]

|SQL直実行|dataSource.query()|配列が戻り値|
|SQL直実行でバイド|dataSource.query("xxx = ?",[1])|PHPと同じじゃ!|
|SQLに近いが独自|dataSource.createQueryBuilder(Entity).getMany()||
|カウント|dataSource.getRepository(Trips).count({ where: { carId: carId } })|条件付けないならcount()あるが、一度に取得できるfindAndCountがよい|
|where条件直記載|dataSource.getRepository(PosRecords).count({where: {recorded: Raw((alias) => `${alias} between :from AND :to`,{from: '2022-10-1', to: '2022-11-1'})}});|toとfromをパラメータ化|

*既存DBからEntity生成 [#i6414004]

https://www.npmjs.com/package/typeorm-model-generator

-entity生成

 npx typeorm-model-generator

後はインタラクティブにMySQLを選べばOK!

 npm typeorm-model-generator -h db.example.com -d <database>  -u root -x [password] -e mariadb
 npm typeorm-model-generator -h 127.0.0.1 -d <database>  -u root -x [password] -e mariadb


*find/findBy [#t5d4fbd1]

findはrelationなどいろいろ設定できるにたいし、findByは条件のみ記載できる。そのためorderなどを指定する場合は必然的にfindを使うことになり、findOneBy以外はあまり使わないんではないか?
Oneはその1レコードバージョンでAndCountだと件数も取れる

|in条件|In(array)|

*参考サイト [#c238c89a]

**ManyToMany [#x42985f8]

https://zenn.dev/msksgm/articles/20211124-typeorm-many2many

自然に任せると勝手にテーブル推定してわけわからんので指定すること!StoreテーブルのPrefectureがこれ!

  @ManyToMany(() => Prefecture)
  @JoinTable({
      name: "store_prefecture", // table name for the junction table of this relation
      joinColumn: {
          name: "store_id",
          referencedColumnName: "id"
      },
      inverseJoinColumn: {
          name: "prefecture_id",
          referencedColumnName: "id"
      }
  })

*トラブルシューティング [#y7ce6745]

**migrationテーブル [#p8995ff9]

-一度でも実行するとmigrationsテーブルが作成される。

***すでにDBがあるのにmigrationsテーブルがない(または消した)場合。 [#j3a4a0de]

テーブルあるのに作ろうとしてエラー。




**migrationでdatetimeのデフォルト値エラー [#tbe63378]

-CURRENT_TIMESTAMP(6)が生成される。

 create table test (`created` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(6)

-CURRENT_TIMESTAMP()ならOK

 create table test (`created` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(6)

-同じ列の型がすべて揃ってないといけないので以下で解決

  @UpdateDateColumn({ name: 'modified', type: 'datetime', width: 6, precision: 0})

トップ   編集 差分 履歴 添付 複製 名前変更 リロード   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS