javascript - Sequelize保存在多个表中

标签 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
});

最佳答案

我认为最接近的尝试是 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 也可以处理您的情况,但我还没有使用过此功能;在上面的文档中搜索“连接表中的其他属性”)

关于javascript - Sequelize保存在多个表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28897708/

相关文章:

javascript - 我如何使用 knexjs(MySQL) 批量删除。我在匹配单个字段的数组中有条目

node.js - 休息 api 上的事务

javascript - 如何在 promise 中包装 google oauth 授权回调?

java - 如何在java web应用程序中的pdf报告中绘制图表

javascript - 如何指定哪些 Require.js 模块是用优化器压缩的,哪些不是?

node.js - 为什么经典模块解析无法找到我已安装的模块之一?

mysql - 如何防止sequelizer删除数据库

mysql - Sequelize — 对 DATE 字段使用 UNIX 时间戳

javascript - 如何将这种积极的后向断言转换为前向断言?

c# - 检查 web 表单是否在 javascript 中关闭/刷新