我是 bookshelf.js 的新手,我正在尝试从两个表建立一对多关系,当我想从 postman 那里获取数据时,它会抛出以下错误:
“编译 SELECT 查询时检测到未定义绑定(bind):选择 customer_order_line
。* from customer_order_line
where customer_order_line
。id_order_line
在 (?)"
这是我的 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);
客户订单行:
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 的命名约定,则在指定关系时必须明确给出主键和外键。
浏览本教程博客 nodejs with bookshelfjs mysql作者:Qawelesizwe Mlilo。
关于mysql - 编译 SELECT 查询时检测到未定义的绑定(bind) :,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44851435/