简体   繁体   English

1:m问题(使用belongsTo和hasMany)。 结果未反映建议的模型

[英]Issue with 1:m (using belongsTo and hasMany). Result doesn't reflect proposed model

I have a simple sample app where I am trying to setup a 1 to many relationship between 2 tables. 我有一个简单的示例应用程序,试图在2个表之间设置1对多的关系。 I am using sequelize with mssql (tedious). 我正在使用mssql的续集(乏味)。 I have no tables in the database when I start. 启动时数据库中没有表。 I connect to the database successfully and then try you create/sync the models to the database. 我成功连接到数据库,然后尝试将模型创建/同步到数据库。

I have provided my code here to see if anyone has any ideas why I am not able to get the desired result. 我在这里提供了我的代码,以查看是否有人对我无法获得期望的结果有任何想法。 I have seen some people is instanceMethods and classMethods and create some object called associate , but I see nothing in the documentation about that. 我见过有人是instanceMethodsclassMethods,并创建了一个名为associate的对象,但是我在文档中什么都没有看到。 What am I missing here? 我在这里想念什么? I simply want my Items collection to be populated when I query for my Project. 我只是想在查询项目时填充我的Items集合。 Am I setting up the association correctly? 我是否正确设置了关联?

I even considered using belongsToMany as follows but it didn't seem to work for me. 我什至考虑如下使用belongsToMany ,但这似乎对我不起作用。

project.belongsToMany(workitem, {through: 'ProjectWorkItem', as: 'Items', foreignKey: 'workitemId'});
workitem.belongsToMany(project, {through: 'ProjectWorkItem', as: 'Projects', foreignKey: 'projectId'});

index.js index.js

const Sequelize = require('sequelize');

var sequelize = new Sequelize('mssql://username:password@localhost:1433/sequelize-test')

sequelize
    .authenticate()
    .then(function (err) {
        const services = require('./models');
        services(sequelize);
        console.log('Connection has been established successfully.');
    })
    .catch(function (err) {
        console.log('Unable to connect to the database:', err);
    });

models\\index.js 型号\\ index.js

'use strict';
const WorkItem = require('./workitem-model');
const Project = require('./project-model');


module.exports = function (sequelize) {

  console.log('Pre-configure start');
  const project = Project(sequelize);
  const workitem = WorkItem(sequelize);

  var projectInstance = project.build({
    title: 'very important project',
    description: 'Some description'
  });

  projectInstance
    .save()
    .then(function (savedProject) {
      var itemInstance = workitem.build({
        text: "abc",
        projectId: savedProject.id
      });
      itemInstance
        .save()
        .then(function () {
          project.
          findById(savedProject.id)
            .then(function (dbProject) {

              console.log(dbProject.title);
              // THIS RETURNS UNDEFINED - SHOULDN'T THERE BE DATA
              console.log(dbProject.Items);  // <-------------
            });
        });
    });
};

models\\workitem.js 型号\\ workitem.js

'use strict';

const Sequelize = require('sequelize');
const Project = require('./project-model');

module.exports = function (sequelize) {
  const workitem = sequelize.define('workitems', {
    text: {
      type: Sequelize.STRING,
      allowNull: false
    }
  }, {
    freezeTableName: true
  });

  const project = Project(sequelize);
  workitem.belongsTo(project);
  project.hasMany(workitem, {
    as: 'Items'
  });

  workitem.sync();

  return workitem;
};

models\\project.js 型号\\ project.js

'use strict';   

const Sequelize = require('sequelize');

module.exports = function (sequelize) {
  const project = sequelize.define('projects', {
    title: {
      type: Sequelize.STRING,
      allowNull: false
    },
    description: {
      type: Sequelize.STRING,
      allowNull: false
    }
  }, {
    freezeTableName: true,

  });

  project.sync();

  return project;
};
'use strict';
const WorkItem = require('./workitem-model');
const Project = require('./project-model');

module.exports = function (sequelize) {

  console.log('Pre-configure start');
  const project = Project(sequelize);
  const workitem = WorkItem(sequelize);

  var projectInstance = project.build({
    title: 'very important project',
    description: 'Some description'
  });

  return projectInstance
    .save()
    .then(function (savedProject) {
      console.log(savedProject); // check values here. id might be in nested dataValues object e.g. savedProject.dataValues.id;
      var itemInstance = workitem.build({
        text: "abc",
        projectId: savedProject.id
      });
      return itemInstance.save();
    }).then(function (myWorkItem) {
      return project.
      findById(myWorkItem.projectId);
    }).then(function (dbProject) {
      console.log(dbProject.title);
      // THIS RETURNS UNDEFINED - SHOULDN'T THERE BE DATA
      console.log(dbProject.Items); // <-------------
      return dbProject;
    });
};

I figured it out with a little digging on similar posts on StackOverflow :) Posting the updated code in case any one else needs something similar. 我通过对StackOverflow上的类似文章进行了一点挖掘来弄清楚:)发布更新的代码,以防其他人需要类似的东西。 The interesting part is that I had to setup a method to do the relationship binding, and then call the associate methods after all of the models had been setup. 有趣的是,我必须设置一个方法来进行关系绑定,然后在所有模型都设置好之后调用关联方法。 Additionally, I had to do a sync on sequelize at the end of the process not during, because of all the inter-relations. 另外,由于所有的相互关系,我必须在过程的最后而不是在过程的最后进行同步。 It makes sense to me now but it was a pain to figure out. 现在对我来说很有意义,但要弄清楚这是很痛苦的。

index.js index.js

const Sequelize = require('sequelize');

var sequelize = new Sequelize('mssql://username:password@localhost:1433/sequelize-test')

sequelize
    .authenticate()
    .then(function (err) {
        const services = require('./models');
        services(sequelize);
        console.log('Connection has been established successfully.');
    })
    .catch(function (err) {
        console.log('Unable to connect to the database:', err);
    });

models\\workitem-model.js 型号\\工作项,model.js

'use strict';

const Sequelize = require('sequelize');

module.exports = function (sequelize) {
  const workitem = sequelize.define('workitems', {
    text: {
      type: Sequelize.STRING,
      allowNull: false
    }
  }, {
    classMethods: {
      associate(models) {
        workitem.belongsTo(models.projects);
      }
    },
    freezeTableName: true
  });

  return workitem;
};

models\\project-model.js 型号\\项目model.js

'use strict';

const Sequelize = require('sequelize');

module.exports = function (sequelize) {
  const project = sequelize.define('projects', {
    title: {
      type: Sequelize.STRING,
      allowNull: false
    },
    description: {
      type: Sequelize.STRING,
      allowNull: false
    }
  }, {
    classMethods: {
      associate(models) {
        project.hasMany(models.workitems, {
          as: 'Items'
        });
      }
    },
    freezeTableName: true,
  });

  return project;
};

models\\index.js 型号\\ index.js

'use strict';
const WorkItem = require('./workitem-model');
const Project = require('./project-model');

module.exports = function (sequelize) {

  console.log('Pre-configure start');
  const project = Project(sequelize);
  const workitem = WorkItem(sequelize);

  // Setup relationships
  const models = sequelize.models;

  Object.keys(models)
    .map(name => models[name])
    .filter(model => model.associate)
    .forEach(model => model.associate(models));

  sequelize.sync();

  var projectInstance = project.build({
    title: 'very important project',
    description: 'Some description'
  });

  return projectInstance
    .save()
    .then(function (savedProject) {

      var itemInstance = workitem.build({
        text: "abc",
        projectId: savedProject.id
      });
      return itemInstance.save();
    }).then(function (myWorkItem) {
      return project.
      findById(myWorkItem.projectId);
    }).then(function (dbProject) {

      dbProject.getItems().then(function (items) {
        console.log(items); // <------- Associated Item data returned
      });

      return dbProject;
    });
};

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

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