【问题标题】:Bookshelf js fetchAll withRelated option returns empty relation objectBookshelf js fetchAll withRelated 选项返回空关系对象
【发布时间】:2016-02-16 19:15:27
【问题描述】:

当我.fetchAll({ withRelated: 'backfire' }); 时,我最终在输出中得到一个名为 backfire 的属性,其值为 {}。在 knex 调试模式下,我清楚地看到 select "backfire".* from "backfire" where "backfire"."id" in (?); 在复制/粘贴到 sqlite3 控制台时有效(当然是在输入有效 ID 之后)。所以我知道我的模型一定是正确的。

Knex 迁移

exports.up = function(knex, Promise) {
  return knex.schema.createTable("backfire", function(table) {
    table.increments("id").primary();
    table.string("response").notNullable();
    table.string("created_by").notNullable();
    table.timestamps();
}).then(function(){
        return knex.schema.createTable("backfireTrigger", function(table) {
            table.increments("id").primary();
            table.string("trigger").notNullable();
            table.integer("backfire_id").unsigned().notNullable().references("id").inTable("backfire");
            table.string("created_by").notNullable();
            table.timestamps();
        });
    });
};

Models.js

module.exports = function(bookshelf) {

var Backfire = bookshelf.Model.extend({
    tableName: 'backfire',
    backfireTriggers: function() {
      return this.hasMany(BackfireTrigger);
    }
});

var BackfireTrigger = bookshelf.Model.extend({
    tableName: 'backfireTrigger',
    backfire: function() {
      return this.belongsTo(Backfire);
    }
});

return {
  Backfire: Backfire,
  BackfireTrigger: BackfireTrigger
};

}

我的用法

function getAllTriggers() {
    var self = this;
    return new self.models.BackfireTrigger()
    .fetchAll({
        withRelated: ['backfire']
    });
}

【问题讨论】:

  • 您使用的是哪个底层数据库?我在 SQLite3 上试过你的代码没有问题:(gist.github.com/flaviodesousa/1465625173202fda563e)
  • SQLite3 也许我还有另一个问题。感谢您在本周寻找和挖掘更多信息并报告。
  • 运气好吗@VictorioBerra ?
  • 我没有,但我可能需要一段时间才能再次处理此问题。有没有办法“关闭”这个问题?

标签: node.js bookshelf.js knex.js


【解决方案1】:

查看文档,似乎“withRelated”字段不是 model.fetchAll 的选项,对于 model.fetch 也是如此。我自己也遇到了这个问题。如果您使用 debug : true 运行 knex,您可以看到它只会查询您正在获取的表,而不是关系。

http://bookshelfjs.org/#Model-instance-fetchAll

【讨论】:

  • 恕我直言,这是书架的一个相当大的问题。我想获取每个事件及其邀请列表的列表。如果没有这个功能,我不确定如何做到这一点
  • 这解决了这个问题:npmjs.com/package/bookshelf-eloquent
【解决方案2】:

我自己是 Bookshelf.js 的新手,但我认为,这可以使用 Collections (http://bookshelfjs.org/#Collection) 来实现。

var BackfireTriggers = bookshelf.Collection.extend({
    model: BackfireTrigger
});

BackfireTriggers.forge().fetch({ withRelated: 'backfire' }).then(…);

【讨论】:

    猜你喜欢
    • 2019-10-10
    • 1970-01-01
    • 2016-02-27
    • 1970-01-01
    • 2017-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-02
    相关资源
    最近更新 更多