简体   繁体   English

Sequelize:插入值时一对多关系不起作用

[英]Sequelize : One-to-Many relationship not working when inserting values

I got a One-to-Many relationship between two objects : Dashboard, and Chart, described like this : 我在两个对象(仪表板和图表)之间建立了一对多关系,描述如下:

module.exports = function (sequelize, DataTypes) {
  const Dashboard = sequelize.define('Dashboard', {
      id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    title: {
      type: DataTypes.STRING
    }
  });

  Dashboard.associate = (models) => {
    Dashboard.belongsTo(models.User, {
      foreignKey: 'user_id',
      targetKey: 'id'
    });

    Dashboard.hasMany(models.Chart, {
      foreignKey: 'dashboard_id',
      sourceKey: 'id'
    });
  };

  return Dashboard;
};

And : 和:

module.exports = function(sequelize, DataTypes) {
  var Chart = sequelize.define('Chart', {
      id: {
        type: DataTypes.INTEGER(32),
        primaryKey: true,
        autoIncrement: true
      },
      title: {
        type: DataTypes.STRING,
        allowNull: false
      },
      x_title: {
        type: DataTypes.STRING
      },
      y_title: {
        type: DataTypes.STRING
      },
      data_type: {
        type: DataTypes.STRING,
        allowNull: false
      },
      data_value: {
        type: DataTypes.STRING,
        allowNull: false
      },
      filters: {
        type: DataTypes.TEXT,
        allowNull: false
      }
    }
  );

  Chart.associate = (models) => {
    Chart.belongsTo(models.Dashboard, {
      foreignKey: 'dashboard_id',
      targetKey: 'id'
    });
  };

  return Chart;
};

So when I want to add a new Dashboard with several charts like this : 因此,当我想添加带有多个图表的新仪表板时,如下所示:

models.Dashboard.create({
    user_id: 1,
    title: 'Dashboard title',
    charts: [
      {
        title: 'time',
        x_title: 'Days',
        y_title: 'Count',
        data_type: 'count',
        data_value: 'visit',
        filters: '[{"type":"project","values":["1"]},{"type":"language","values":["french"]},{"type":"satisfaction","values":[1,2,3]}]'
      },
      {
        title: 'indicator',
        x_title: '',
        y_title: '',
        data_type: 'count',
        data_value: 'visit',
        filters: '[{"type":"project","values":["1","2","3","4","5","6"]},{"type":"language","values":["french"]}]'
      }
    ]
  }, { include: [models.Chart] }).then(() => {
    res.send({
      'message': 'Dashboard loaded !'
    });
  });

The dashboard is inserted into the database, but no charts inserted as well... What is the best way to add records with a one-to-many association using Sequelize ? 仪表板已插入数据库中,但也未插入图表...使用Sequelize通过一对多关联添加记录的最佳方法是什么? I just try and try, and read all docs ( http://docs.sequelizejs.com/manual/tutorial/associations.html#creating-with-associations ) but I don't understand this problematic behaviour... 我只是尝试尝试,并阅读了所有文档( http://docs.sequelizejs.com/manual/tutorial/associations.html#creating-with-associations ),但我不理解这种有问题的行为...

Thank's for your help and your enlightening ! 感谢您的帮助和启发!

In the defined association 在定义的关联中

Dashboard.hasMany(models.Chart, {
      foreignKey: 'dashboard_id',
      sourceKey: 'id'
    });

the foreignKey is mentioned as dashboard_id but there is no dashboard_id in the Chart model. foreignKey被提到为dashboard_id但在Chart模型中没有dashboard_id

The following code works 以下代码有效

const Dashboard = sequelize.define('dashboard', {
  title: Sequelize.STRING,
});

const Chart = sequelize.define('chart', {
  dashboard_id: Sequelize.INTEGER,
  title: Sequelize.STRING,
});

Dashboard.hasMany(Chart, {
  foreignKey: 'dashboard_id',
  sourceKey: 'id'
});
Dashboard.create({
  title: 'one',
  charts: [
    { title: 'title1' },
    { title: 'title2' }
  ]
}, { include: [Chart] }).then((result) => {
  console.log(result);
});

Thank's you for your help, but I need a bidirectional One-To-Many association. 谢谢您的帮助,但我需要一个双向的一对多关联。

By doing your way, I still got the same problem... I don't understand why, maybe it's because I use Sequelize CLI with one JS file per object definition... Or the Sequelize sync function is not called at the right moment. 通过您的方式,我仍然遇到同样的问题...我不明白为什么,也许是因为我使用Sequelize CLI和每个对象定义一个JS文件...或者在适当的时候未调用Sequelize sync函数。

The weird thing is that when I insert the Dashboard first and then I insert the charts by defining their dashboard_id it works well. 奇怪的是,当我先插入仪表板,然后通过定义其dashboard_id插入图表时,它运行良好。 Like this: 像这样:

models.Dashboard.create({ 
    user_id: 1,
    title: 'Visites Histopad'
}).then((dashboard) => {
    models.Chart.bulkCreate([{
        dashboard_id: dashboard.id,
        title: 'time',
        x_title: 'Days',
        y_title: 'Count',
        data_type: 'count',
        data_value: 'visit',
        filters: '[{"type":"project","values":["1"]},{"type":"language","values":["french"]},{"type":"satisfaction","values":[1,2,3]}]'
      },
      {
        dashboard_id: dashboard.id,
        title: 'indicator',
        x_title: '',
        y_title: '',
        data_type: 'count',
        data_value: 'visit',
        filters: '[{"type":"project","values":["1","2","3","4","5","6"]},{"type":"language","values":["french"]}]'
      }
    ]).then(() => {
      res.send({
        'message': 'Dashboard loaded !'
      });
    });
  });

Ok, I figured out... I was using an old version of Sequelize, because seuquelize-cli load the 2.0.0-rc8 version and not the last one (4.0.0). 好的,我知道了...我使用的是旧版本的Sequelize,因为seuquelize-cli加载了2.0.0-rc8版本,而不是最后一个版本(4.0.0)。 So everything works perfectly now. 所以现在一切正常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM