【问题标题】:Sequelize: Error: Error: Table1 is not associated to Table2Sequelize:错误:错误:Table1 未关联到 Table2
【发布时间】:2017-06-25 08:52:27
【问题描述】:

我正在尝试使用 sequelize 创建以下关联,但我不断收到以下错误“错误:错误:客户未与订单关联!”。根据我在文档中找到的内容,我有双向关联。我对问题可能是什么感到困惑,因为当我查看数据库表时,我可以看到外键。对于此示例,我试图提取与特定订单关联的订单和客户。从技术上讲,我可以执行三个单独的 db pull,但与连接相比,这似乎效率低下。

'use strict';

module.exports = function(sequelize, DataTypes) {
  var user = sequelize.define('user', {
    username: DataTypes.STRING(30), //remove
    password: DataTypes.STRING(255),
    emailaddress: DataTypes.STRING(255),
    firstname: DataTypes.STRING(30),
    middlename: DataTypes.STRING(30), //remove
    lastname: DataTypes.STRING(30),
    approve: DataTypes.BOOLEAN,
    roles: DataTypes.STRING(50),
    isactive: DataTypes.BOOLEAN
  }, {
    classMethods: {
      associate: function(models) {
        // associations can be defined here
        this.hasMany(models.order);
      }
    }
  });

  user.hook('afterCreate', function(usr, options) {
      //hash the password

      return user.update({ password: passwd }, {
        where: {
          id: usr.id
        }
      });
  });

  return user;
};



'use strict';
module.exports = function(sequelize, DataTypes) {
  var order = sequelize.define('order', {
    ponumber: DataTypes.STRING(30), //remove
    orderdate: DataTypes.DATE,
    shippingmethod: DataTypes.STRING(30),
    shippingterms: DataTypes.STRING(30),
    deliverydate: DataTypes.DATE,
    paymentterms: DataTypes.STRING(30),
    overridediscount: DataTypes.BOOLEAN,
    shippingaddress: DataTypes.STRING(30),
    shippingcity: DataTypes.STRING(30),
    shippingstate: DataTypes.STRING(20),
    shippingzipcode: DataTypes.STRING(10),
    isactive: DataTypes.BOOLEAN
  }, {
      associate: function(models) {
        // associations can be defined here
        this.belongsTo(models.user);
        this.belongsTo(models.customer);
      }
  });

  order.hook('afterCreate', function(ord, options) {
      //generate po number

      return order.update({ ponumber: ponumbr }, {
        where: {
          id: ord.id
        }//,
        //transaction: options.transaction
      });
  });

  return order;
};


'use strict';
module.exports = function(sequelize, DataTypes) {
  var customer = sequelize.define('customer', {
    customernumber: DataTypes.STRING(30), //remove
    customerspecificationid: DataTypes.INTEGER,
    customertypeid: DataTypes.INTEGER,
    sportid: DataTypes.INTEGER,
    customername: DataTypes.STRING(20), //remove
    address: DataTypes.STRING(30),
    city: DataTypes.STRING(30),
    state: DataTypes.STRING(30),
    zipcode: DataTypes.STRING(30),
    ordercomplete: DataTypes.BOOLEAN,
    isactive: DataTypes.BOOLEAN
  }, {
      associate: function(models) {
          // associations can be defined here
        this.hasMany(models.order);
      }
  });

  customer.hook('afterCreate', function(cust, options) {
      //generate the customer number

        return customer.update({ customernumber: custnumber }, {
        where: {
          id: cust.id
        }
      });
  });

  return customer;
};


Here is the constructor and method inside of a repository class I want to join 

constructor(model){
    super(model.order);
    this.currentmodel = model;
}


findById(id){
    let that = this;
    return new Promise(
        function(resolve, reject) {
            that.model.find({
                where: { id: id },
                include: [ that.currentmodel.customer, that.currentmodel.user ]
            })
            .then(function(order){
                resolve(order);
            })
            .catch(function(err){
                reject(err);
            })
    });
}

我已查看文档并在互联网上搜索以寻找解决此问题的方法,但我没有找到任何答案。有人可以解释一下我可能会错过什么吗?

对于上面的示例,我试图通过主键检索绑定到订单记录的用户和客户。到目前为止,我发现的所有 findBy 场景都是获取与客户和用户相关的订单列表。为了检索外键与该订单相关联的订单和客户,我需要进行哪些更改?

【问题讨论】:

    标签: mysql node.js sequelize.js


    【解决方案1】:

    问题可能在于您如何设置关联,请提及您的策略。

    如果您使用 express index.js 文件设置然后查询http://docs.sequelizejs.com/en/1.7.0/articles/express/,则以下工作正常

    'use strict';
    module.exports = function(sequelize, DataTypes) {
      var customer = sequelize.define('customer', {
        customernumber: DataTypes.STRING(30), //remove
        customerspecificationid: DataTypes.INTEGER,
        customertypeid: DataTypes.INTEGER,
        sportid: DataTypes.INTEGER,
        customername: DataTypes.STRING(20), //remove
        address: DataTypes.STRING(30),
        city: DataTypes.STRING(30),
        state: DataTypes.STRING(30),
        zipcode: DataTypes.STRING(30),
        ordercomplete: DataTypes.BOOLEAN,
        isactive: DataTypes.BOOLEAN
      }, {
          associate: function(models) {
              // associations can be defined here
            models.customer.hasMany(models.order);
          }
      });
    
      customer.hook('afterCreate', function(cust, options) {
          //generate the customer number
    
            return customer.update({ customernumber: custnumber }, {
            where: {
              id: cust.id
            }
          });
      });
    
      return customer;
    };
    
    
    'use strict';
    module.exports = function(sequelize, DataTypes) {
      var order = sequelize.define('order', {
        ponumber: DataTypes.STRING(30), //remove
        orderdate: DataTypes.DATE,
        shippingmethod: DataTypes.STRING(30),
        shippingterms: DataTypes.STRING(30),
        deliverydate: DataTypes.DATE,
        paymentterms: DataTypes.STRING(30),
        overridediscount: DataTypes.BOOLEAN,
        shippingaddress: DataTypes.STRING(30),
        shippingcity: DataTypes.STRING(30),
        shippingstate: DataTypes.STRING(20),
        shippingzipcode: DataTypes.STRING(10),
        isactive: DataTypes.BOOLEAN
      }, {
          associate: function(models) {
            // associations can be defined here
            models.order.belongsTo(models.user);
            models.order.belongsTo(models.customer);
          }
      });
    
      order.hook('afterCreate', function(ord, options) {
          //generate po number
    
          return order.update({ ponumber: ponumbr }, {
            where: {
              id: ord.id
            }//,
            //transaction: options.transaction
          });
      });
    
      return order;
    };
    
    'use strict';
    
    module.exports = function(sequelize, DataTypes) {
      var user = sequelize.define('user', {
        username: DataTypes.STRING(30), //remove
        password: DataTypes.STRING(255),
        emailaddress: DataTypes.STRING(255),
        firstname: DataTypes.STRING(30),
        middlename: DataTypes.STRING(30), //remove
        lastname: DataTypes.STRING(30),
        approve: DataTypes.BOOLEAN,
        roles: DataTypes.STRING(50),
        isactive: DataTypes.BOOLEAN
      }, {
        classMethods: {
          associate: function(models) {
            // associations can be defined here
            models.user.hasMany(models.order);
          }
        }
      });
    
      user.hook('afterCreate', function(usr, options) {
          //hash the password
    
          return user.update({ password: passwd }, {
            where: {
              id: usr.id
            }
          });
      });
    
      return user;
    };
    

    // 关联路由的 index.js 文件

    var fs        = require('fs')
        , path      = require('path')
        , Sequelize = require('sequelize')
        , lodash    = require('lodash')
        , sequelize = new Sequelize('sequelize_test', 'root', 'root')
        , db        = {} 
    
      fs.readdirSync(__dirname)
        .filter(function(file) {
          return (file.indexOf('.') !== 0) && (file !== 'index.js')
        })
        .forEach(function(file) {
          var model = sequelize.import(path.join(__dirname, file))
          db[model.name] = model
        })
    
      Object.keys(db).forEach(function(modelName) {
        if (db[modelName].options.hasOwnProperty('associate')) {
          db[modelName].options.associate(db)
        }
      })
      // sequelize.sync({force: true})
      module.exports = lodash.extend({
        sequelize: sequelize,
        Sequelize: Sequelize
      }, db)
    

    将上面的数据库代码放在数据库文件夹中的相应文件中或任何您喜欢的名称中,然后您就可以使用您的查询

    var db = require('./db');

    db.order.find({
                where: { id: 0 },
                include: [ db.customer, db.user ]
            })
            .then(function(order){
                console.log(order)
            })
    

    【讨论】:

    • 做到了。太感谢了。还有一个问题,如果你不介意的话。到目前为止,我一直在创建或更新记录之前通过设置属性来添加外键,例如'...id ='。是否有这样做的首选方法,或者这种方法是否可以接受?
    • 我确实清楚地知道了您的问题,但是如果您已经有了要关联的模型的 ID,并且您可以使用您的方法使用 id 创建记录以进行简单的关联,例如一对多或一对到一个
    猜你喜欢
    • 2016-04-11
    • 1970-01-01
    • 1970-01-01
    • 2014-03-17
    • 1970-01-01
    • 2017-11-14
    • 2018-06-14
    • 1970-01-01
    • 2018-01-03
    相关资源
    最近更新 更多