gpt4 book ai didi

node.js - 如何在 Bookshelf 中获取已连接模型的模型?

转载 作者:太空宇宙 更新时间:2023-11-03 23:05:09 26 4
gpt4 key购买 nike

我有一个针对股票和快照的一对多数据模型。

// 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);

但是,当我尝试从 Stock 中获取多个快照时,如下所示:

// 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查询。但是,快照数组是空的。我错过了什么?

谢谢!

最佳答案

如果您使用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')
}
})

关于node.js - 如何在 Bookshelf 中获取已连接模型的模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36534494/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com