我开始使用Node.JS,bookshelf.js和bookshelf-pagemaker。
我的数据库包含2个表格: - 具有3个主行的资产(idasset,name,idarrangement) - Arrangement_details有2个主行(idarrangement_details,material)
我想获得所有资产,例如材料= 2。
资产模型:
var AssetsCollection = DB.Model.extend({ tableName: 'assets', idAttribute: 'idassets', arrangementdetails: function () { return this.belongsTo(ArrangementDetail, 'idarrangement_details'); } });
我已尝试过此代码,但由于未加入Arrangedetails,因此崩溃了。
var pm = require('bookshelf-pagemaker')(DB); pm(AssetsCollection.AssetsCollection) .forge() .limit(req.params.limit) .offset(req.params.page) .query(function(qb){ qb.where('Arrangement_details.material', '=', 4) }) .paginate({request: req, withRelated: ['arrangementdetails']) .end({}) .then(function (results) { callback(null, {code: 200 , res: results}); });
可以这样做吗?
此致 DarKou
答案 0 :(得分:0)
您需要加入表格才能搜索相关表格。如果没有看到你的表格结构,这将在黑暗中有所作为,但你应该在查询回调中使用连接以及类似于以下内容的地方。要清楚的是书架或页面制作者都没有功能问题,而你正在努力实现目标。
您似乎有2个表,其中包含以下内容
表格:资产, idAttribute :idassets
表格:Arrangement_details, idAttribute :idarrangement_details
var pm = require('bookshelf-pagemaker')(DB);
pm(AssetsCollection.AssetsCollection)
.forge()
//.limit(req.params.limit) -- not needed as you are already passing req to paginate
//.offset(req.params.page) -- not needed as you are already passing req to paginate
.query(function(qb){
qb.join('Arrangement_details', 'Arrangement_details.idarrangement_details', '=', 'assets.idarrangement_details')
.where('Arrangement_details.material', '=', 4);
})
.paginate({request: req, withRelated: ['arrangementdetails'])
.end()
.then(function (results) {
callback(null, {code: 200 , res: results});
});
但我鼓励你使用较少混淆的名称来表示你的表/字段,如下所示,其中id是两者的idAttribute,details_id是belongsTo关系的外键
var AssetsCollection = DB.Model.extend({
tableName: 'assets',
idAttribute: 'id',
arrangementDetails: function () {
return this.belongsTo(ArrangementDetail, 'details_id');
}
});
var ArrangementDetail = DB.Model.extend({
tableName: 'arrangement_details',
idAttribute: 'id'
});
var pm = require('bookshelf-pagemaker')(DB);
pm(AssetsCollection.AssetsCollection)
.forge()
.query(function(qb){
qb.join('arrangement_details', 'arrangement_details.id', '=', 'assets.details_id')
.where('arrangement_details.material', '=', 4);
})
.paginate({request: req, withRelated: ['arrangementDetails'])
.end()
.then(function (results) {
callback(null, {code: 200 , res: results});
});