2017-07-07 5 views
1

デフォルトでは、sequelizeはmanyAttributeとmanyAllの関係の結合テーブルでcreatedAtとupdatedAtカラムを作成しますが、createdAtカラムを使用し、行が作成されたときに自動的に設定します。結合テーブルのcreatedAtカラムのみ

カスタムUserJobモデル:

const UserJob = sequelize.define('UserJob', { 
    createdAt: DataTypes.DATE 
}, { 
    timestamps: false 
}); 
UserJob.beforeCreate((userJob, options) => { 
    console.log('before create'); 
    userJob.createdAt = new Date(); 
}); 
return UserJob; 

協会:

User.belongsToMany(models.Job, {through: UserJob, foreignKey: 'user_id'}); 
Job.belongsToMany(models.User, {through: UserJob, foreignKey: 'job_id'}); 

それはcreatedAtを設定していない、私は何をすべき?あなたは、特定のタイムスタンプ をしたくない場合は、だからあなたの場合のために、あなたは、falseに列が存在しません。そのようにupdatedAtを設定することができ

const Foo = sequelize.define('foo', { /* bla */ 
    { // don't forget to enable timestamps! 
    timestamps: true, 
    // I don't want createdAt 
    createdAt: false, 
    // I want updatedAt to actually be called updateTimestamp 
    updatedAt: 'updateTimestamp' 
}) 

として、あなたのモデルを定義する必要がありsequelize suggestsとして

+0

日付は取得できませんか?または 'userJob.createdAt'に挿入されているもの –

+0

作成前に呼び出されず、createdAtがnullです。 –

答えて

1

、 。 フックを使うよりももっとクリーンになります。

関連する問題