编译 SELECT 查询时检测到未定义的绑定:

Undefined binding detected when compiling SELECT query:

我是 bookshelf.js 的新手,我正在尝试从两个表建立一对多关系,当我想从邮递员那里获取数据时,它会抛出以下错误:

"Undefined binding(s) detected when compiling SELECT query: select customer_order_line.* from customer_order_line where customer_order_line.id_order_line in (?)"

这是我的 customer_order 的数据模型:

 var customer_order = db.Model.extend({
    tableName: 'customer_order',
    hasTimestamps: true,

    orders : function() {
        return this.hasMany('order_line', 'id_order_line');
    },

    payment : function() {
        return this.belongsTo('payment','id_payment');
    }

})

module.exports = db.model('customer_order', customer_order);

customer_order_行:

var order_line = db.Model.extend({
    tableName: 'customer_order_line',


    product : function(){
        return this.belongsTo('Product','id_products');
    },

    order : function(){
        return this.belongsTo('customer_order','id_customer_order');
    }
})

module.exports = db.model('order_line', order_line);

这是我获取数据的函数:

 getOrders: function(req, res, next) {
    Customer_orders.forge()
    .fetch({withRelated: ['orders']})
    .then(function (collection){

      res.json({
        error : false,
        data : collection.toJSON()
      });
    })
    .catch(function (err){
      res.status(500)
      .json({
        error : true,
        data: {message: err.message}
      });
    });
  }

mysql 个表格:

CREATE TABLE customer_order (
            id_customer_order INT AUTO_INCREMENT NOT NULL,
            id_employee INT NOT NULL,
            id_payment INT NOT NULL,
            total DECIMAL(10,2) NOT NULL,
            status NUMERIC(11) NOT NULL,
            created_at TIMESTAMP NOT NULL,
            updated_at TIMESTAMP NOT NULL,
            PRIMARY KEY (id_customer_order)
);

CREATE TABLE customer_order_line (
            id_order_line INT AUTO_INCREMENT NOT NULL,
            id_customer_order INT NOT NULL,
            id_products INT NOT NULL,
            cost_without_taxes DECIMAL(10,2) NOT NULL,
            cost_with_taxes DECIMAL(10,2) NOT NULL,
            final_price DECIMAL(10,2) NOT NULL,
            quantity NUMERIC(11) NOT NULL,
            total_without_taxes DECIMAL(10,2) NOT NULL,
            total_with_taxes DECIMAL(10,2) NOT NULL,
            total DECIMAL(10,2) NOT NULL,
            status NUMERIC(11) NOT NULL,
            PRIMARY KEY (id_order_line)
);

我修改了你的customer_order模型如下

var customer_order = db.Model.extend({
tableName: 'customer_order',
hasTimestamps: true,

    orders : function() {
       return this.hasMany('order_line', 'id_customer_order');
       //this must contain the foreign key present inside the order_line table and not id_order_line
    },

    payment : function() {
       return this.belongsTo('payment','id_payment');
    }

})
module.exports = db.model('customer_order', customer_order);

如果您的列名不遵循的命名约定,则在指定关系时必须明确给出主键和外键bookshelf.js.

阅读 Qawelesizwe Mlilo 撰写的教程博客 nodejs with bookshelfjs mysql