Table1与Table2不相关

Table1与Table2不相关

本文介绍了Sequelize:错误:错误:Table1与Table2不相关的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to create the following associations using sequelize but I keep getting the following error "Error: Error: customer is not associated to order!". I have bi-directional associations according to what I found in the documentation. I am confused about what the problem could be because when I look into the database tables I can see the foreign keys. For this example, I am trying to pull the order and customer associated with the particular order. Technically, I could do three seaprate db pull but that seems inefficient as opposed to joins.

'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);
            })
    });
}

我已经查看了文档,并在互联网上搜索了针对此问题的解决方法,但没有找到任何答案.有人可以告诉我我可能会想念的东西吗?

I have reviewed the documentation and searched the internet looking for a fix to this issue but I am not finding any answers. Could someone please shed some light on what I could be missing?

对于上面的示例,我试图通过主键检索与订单记录相关联的用户和客户.到目前为止,我发现的所有findBy方案都将获取与客户和用户相关的订单列表.为了检索订单以及外键与该订单绑定的客户,我需要更改什么?

For the example above, I am trying to retrieve the user and the customer tied to the order record via the primary key. All of the findBy scenarios I have found so far would be getting a list of orders tied to the customer and user. What do I need to change in order to retrieve the order and customer whose foreign keys are tied to this order?

推荐答案

问题可能出在您如何设置关联上,请提及您的策略.

The problem is probably with how you are setting you association, kindly mention your strategy.

如果使用快速index.js文件设置,然后查询 http://docs.sequelizejs.com/en/1.7.0/articles/express/

Following is working fine if you use the express index.js file setup and then query 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文件,您应在其中关联路由

// index.js file where you shall associate the routes

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)

将上面的db代码放在db文件夹中的相应文件中,或将其命名为任意名称,然后就可以使用查询了

Put the above db code in respective files in db folder or whatever you like to name it and then you can use your query

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

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

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

这篇关于Sequelize:错误:错误:Table1与Table2不相关的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 20:07