2016-11-28 3 views
0

私はUserというモデルを持っていますが、それに関連するレコードはUserSettingsです(1対1)。私はUserを作成するとが自動的にのデフォルト値でUserSettingsのレコードを作成するようにしたいと思います。1:1の関係を自動的に作成する方法は?

フックのさまざまな組み合わせ(beforeCreate、beforeValidate、afterCreate)を試しました。何も動作していないようです。

User.createを呼び出してUserSettings関係を含めると機能しますが、デフォルトのオブジェクトを渡して「インクルード」を追加する必要はありません。

思考?

答えて

0

私は1:m + n:mアソシエーションを持っていましたが、あなたのケースでは問題にならないと思います。
現時点では、自動機能があるかどうかわかりませんが、私はその回避策でそれを行いました。
私の場合、それは
キー1だった:私は、私は結果に行き、結果ID新しいLangsで作成したキーを作成した時点では、m個の製品
:ラング
キーnとmは。
その後、Associated ProductsでKeysを作成しました。

export function create(req, res) { 
    return DictKey.create(req.body.body)// Create a Key 
    .then((res)=> { 
     for (var i = 0; i < req.body.langs.length; i++) { 
     DictValue.create({//Create Associated Languages 
      lang_id: req.body.langs[i], 
      key_id: res._id 
     }) 
     } 
     return res; 
    }) 
    .then((key)=>{ 
     return key.addProduct(req.body.products);//Create Products 
    }) 
    .then(respondWithResult(res, 201)) 
    .catch(handleError(res)); 
} 

モデル定義では、何も渡す必要がないようにデフォルト値を設定できます。

'use strict'; 

export default function(sequelize, DataTypes) { 
    return sequelize.define('dict_Keys', { 
    _id: { 
     type: DataTypes.INTEGER, 
     allowNull: false, 
     primaryKey: true, 
     autoIncrement: true 
    }, 
    type: { 
     type: DataTypes.INTEGER, 
     allowNull:false, 
     defaultValue: 0 // DefaultValue if nothing is passed 
    }, 
    },{ 
    tableName: 'Keys' 
    }); 
} 

だからあなたのケースでは、私はこれがあなたの役に立てば幸い

export default function(sequelize, DataTypes) { 
    return sequelize.define('UserSettings', { 
    _id: { 
     type: DataTypes.INTEGER, 
     allowNull: false, 
     primaryKey: true, 
     autoIncrement: true 
    }, 
    YourColumnName: { 
     type: DataTypes.WhatYouWant, 
     allowNull:CaseYouNeed, 
     defaultValue: 0 // DefaultValue if nothing is passed 
    } 
} 


    export function create(req, res) { 
     return User.create(req.body)// Create a User 
     .then((res)=> { 
      UserSettings.create(
      //Create Associated Settings 
      //send with Values or without which the DefaultValues will handle 
) 
      } 
      return res; 
     }) 
     .then(respondWithResult(res, 201)) 
     .catch(handleError(res)); 
    } 

のようなものである可能性があります。

+0

ありがとうございました。私は、インスタンスが作成されるたびにそれを行う前/後のフックを探していました。 – akanieski

関連する問題