LoginSignup
0
0

More than 1 year has passed since last update.

SequelizeでbulkCreateを使用してINSERTする際、値を指定していないAUTO_INCREMENTを付与したカラムの値を取得する

Last updated at Posted at 2022-04-14

初めに

SequelizeでbulkCreateメソッドを使用する際に、AUTO_INCREMENTを付与しているカラムを指定せずに挿入した場合に、thenメソッドの引数に挿入したカラムの値がNULLで格納されていた。
検索した際に日本語の情報が少ないと感じたため、AUTO_INCREMENTを付与したカラムの値を取得する方法を記載する。

■ Sequelizeのバージョン
3.30.4
■ MySQLのバージョン
5.7.37

解決方法

bulkCreateメソッドに以下の記述を追加することで解決した。

individualHooks: true

Model.bulkCreate(
    [ { coulumn: "test" }, { coulumn: "test" } ], 
    { individualHooks: true }
).then((results)=>{
    // 引数resultsに挿入されたAUTO_INCREMENTを付与したカラムの値が格納されている
})

transactionと組み合わせる場合

sequelize.transaction((tx)=> {
     Model.bulkCreate(
         [ { coulumn: "test" }, { coulumn: "test" } ], 
         { transaction: tx, individualHooks: true }
     ).then((results)=>{
      // 引数resultsに挿入されたAUTO_INCREMENTを付与したカラムの値が格納されている
     })
}
0
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
0
0