我有股票和快照的1对多数据模型。
// stock.js
var bookshelf = require('../config');
var Snapshot = require('./snapshot');
var Stock = bookshelf.Model.extend({
tableName: 'stocks',
hasTimestamps: true,
snapshots: function() {
return this.hasMany(Snapshot);
}
});
module.exports = bookshelf.model('Stock', Stock);
每只股票都有许多数据快照。快照属于股票:
var bookshelf = require('../config');
var Stock = require('./stock');
var Snapshot = bookshelf.Model.extend({
tableName: 'snapshots',
hasTimestamps: true,
stock: function() {
return this.belongsTo(Stock);
}
});
module.exports = bookshelf.model('Snapshot', Snapshot);
但是,当我尝试从像这样的股票获取多个快照时:
// report stock
var bookshelf = require('./config');
var Stock = require('./models/stock');
var Snapshot = require('./models/snapshot');
var Promise = require("bluebird");
Stock.fetchAll({
withRelated: ['snapshots'],
debug: true
})
.then(function(collection) {
return collection.mapThen(function(model) {
return model.toJSON();
})
})
.then(function(results) {
console.log(results);
})
.finally(function(r) {
return bookshelf.knex.destroy();
})
.catch(function(e) {
console.log(e);
});
我没有看到任何快照:
{ method: 'select',
options: {},
bindings: [],
sql: 'select "stocks".* from "stocks"' }
{ method: 'select',
options: {},
bindings: [ 1 ],
sql: 'select "snapshots".* from "snapshots" where "snapshots"."stock_id" in (?)' }
[ { id: 1,
name: '...',
symbol: '...',
created_at: 1460285493918,
updated_at: 1460285493918,
snapshots: [] } ]
我希望看到快照和join
查询。但是,快照数组为空。我错过了什么?
谢谢!
答案 0 :(得分:3)
如果您使用的是bookshelf.plugin("registry")
,则需要按字符串名称链接relations。
var bookshelf = require('../config')
var Stock = bookshelf.model('Stock', {
tableName: 'stocks',
hasTimestamps: true,
snapshots: function () {
return this.hasMany('Snapshot')
}
})
var Snapshot = bookshelf.model('Snapshot', {
tableName: 'snapshots',
hasTimestamps: true,
stock: function () {
return this.belongsTo('Stock')
}
})