Sequelize保存在多个表中

时间:2015-03-06 11:20:36

标签: javascript node.js sequelize.js

好吧所以我有一个很大的问题,我不知道如何修复。我的标题有以下设置:

var Title = sequelize.define('title', {
        id: DataTypes.INTEGER,
        name: DataTypes.STRING,
        organization_id: DataTypes.INTEGER

    }, {
        freezeTableName: true,
        instanceMethods: {
            retrieveAll: function (onSuccess, onError) {
                Title.findAll({order: 'Rand'}, {raw: true})
                    .ok(onSuccess).error(onError);
            },
            retrieveById: function (quote_id, onSuccess, onError) {
                Title.find({where: {id: quote_id}}, {raw: true})
                    .success(onSuccess).error(onError);
            },
            add: function (selectedCompetence,onSuccess, onError) {

                var title = {id: null, name: this.dataValues.name, organization_id: this.dataValues.organization_id};
              Title.build(this.dataValues)
                    .save().ok(onSuccess).error(onError);
            },
            updateById: function (quote_id, onSuccess, onError) {
                var id = quote_id;
                var quotes = this.quotes;

                Title.update({quotes: quotes}, {where: {id: id}})
                    .success(onSuccess).error(onError);
            },
            removeById: function (quote_id, onSuccess, onError) {
                Title.destroy({where: {id: quote_id}}).success(onSuccess).error(onError);
            }
        }
    }
),
    Title_has_competence = sequelize.define('title_has_competence', {
        id: DataTypes.INTEGER,
        title_id: DataTypes.INTEGER,
        competence_id: DataTypes.INTEGER,
        competence_level_id: DataTypes.STRING
    },{
        freezeTableName: true,
        instanceMethods: {
            retrieveAll: function (onSuccess, onError) {
                Title_has_competence.findAll({order: 'Rand'}, {raw: true})
                    .ok(onSuccess).error(onError);
            },
            retrieveById: function (quote_id, onSuccess, onError) {
                Title_has_competence.find({where: {id: quote_id}}, {raw: true})
                    .success(onSuccess).error(onError);
            },
            add: function (competence,onSuccess, onError) {
                var ins = {id: null, title_id:competence.title_id, competence_id: competence.id, competence_level_id: competence.level};
                Title_has_competence.build(ins)
                    .save().ok(onSuccess).error(onError);
            },
            updateById: function (quote_id, onSuccess, onError) {
                var id = quote_id;
                var quotes = this.quotes;

                Title_has_competence.update({quotes: quotes}, {where: {id: id}})
                    .success(onSuccess).error(onError);
            },
            removeById: function (quote_id, onSuccess, onError) {
                Title.destroy({where: {id: quote_id}}).success(onSuccess).error(onError);
            }
        }
    });
Title.belongsToMany(Title_has_competence,{foreignKey: 'competence_id'});

在我的系统中,当你创建一个标题时,你会传递一系列能力:

在这种情况下,权限是数组:selectedCompetence一旦创建了标题,我需要遍历selectedCompetence数组并将它们插入到Title_has_competence表中。

我觉得我已经尝试了从Hooks到轻微黑客的一切,但没有任何效果。

有谁能请我朝正确的方向推?

我尝试过的事情:

  Title.build(this.dataValues)
    .save().done(function(err, success, selectedCompetence){
      var i = 0;  // here selectedCompetence is undefined
  });

  Title.build(this.dataValues)
    .save();
Title.hook('afterCreate', function(success,selectedCompetence){
    var i = 0; // here selectedCompetence is an object with other values
})

    Title.create({id: null, name: this.dataValues.name, organization_id:this.dataValues.organization_id}).then(function(title, selectedCompetence)
{
    var i = 0; // once again selectedCompetence is undefined
});

1 个答案:

答案 0 :(得分:2)

我认为最接近的尝试是then()方法。但是在create()之后传递给then-function的参数只是刚创建的对象,没有别的,所以then(function(title, someCompetence) ...无法工作。

您可以尝试这样的事情:

// Let's say you already know the competence IDs
var competenceIds = [ 1, 2, 3 ]

// First, create the title
Title.create({ id: 1, name: 'Some Title' })
  .then(function(createdTitle) {
    // Build an array of promises. Each element waits for one competence
    // to be associated with the title.
    var associationPromises = [];
    competences.forEach(function(competenceId) {

      // associate one competence with the title
      associationPromises.push(Title_has_competence.create({
        title_id: createdTitle.id,
        competence_id: competenceId,
        competence_level_id: 123 // whatever else is on the join table
      })
    });

    // Wait for all the competences to be associated before continuing
    return Sequelize.Promise.all(associationPromises);
  });

这是一种非常低级的方法,当你有复杂的关系时会派上用场(比如连接多个实体的连接表:Title,Competence和Level)。

但通常Sequelize可以自动处理大量此事(请参阅documentation on Relations)。例如,如果您只有Title-Competence关系,那么您可以写一下:

var Title = sequelize.define(...)
var Competence = sequelize.define(...)
Competence.belongsToMany(Title, {through: 'title_has_competence'});
Title.belongsToMany(Competence, {through: 'title_has_competence'});

Title.create({name: 'Some Title'}).then(function(createdTitle) {
  return createdTitle.setCompetences([1, 2, 3]);
});

(注意:我实际上认为Sequelize 也可以处理您的情况,但我还没有使用此功能;在您的联接表中搜索"其他属性"在上面的文档中)