【问题标题】:Unable to get related object in bookshelf.js无法在 bookshelf.js 中获取相关对象
【发布时间】:2015-01-31 15:18:17
【问题描述】:

有谁知道为什么我无法访问给定book相关 author

console.log(book.related('author').toJSON()); 打印一个 empty 对象。

var Book = Bookshelf.Model.extend({

  tableName: 'books',
  hasTimestamps: true,

  author: function() {
    return this.belongsTo(require('./author'));
  },

});

var Author = Bookshelf.Model.extend({

  tableName: 'authors',
  hasTimestamps: true,

  books: function(){
    return this.hasMany(require('./book'), 'author_id');
  },

});

在我的GET /books/{id} 路由处理程序中:

var p = new Book({id: req.params.id}).fetch({
    withRelated: ['author']
  }).then(function(book){

      // THIS PRINTS AN EMPTY OBJECT
      console.log(book.related('author').toJSON());

      return {
        book: internals.renderbook(book)
      };
  });

如果我尝试不打印 .toJSON(),它会显示:

{ attributes: {},
   _previousAttributes: {},
   changed: {},
   relations: {},
   cid: 'c12',
   relatedData: 
    { type: 'belongsTo',
      target: 
       { [Function]
         super_: [Object],
         NotFoundError: [Function: ErrorCtor],
         collection: [Function],
         forge: [Function],
         where: [Function],
         query: [Function],
         fetchAll: [Function],
         extend: [Function],
         __super__: [Object] },
      targetTableName: 'authors',
      targetIdAttribute: 'id',
      foreignKey: 'user_id',
      parentId: 'b3b35d4c-17c3-46bd-90c2-a17fe907b9b8',
      parentTableName: 'books',
      parentIdAttribute: 'id',
      parentFk: undefined } }

【问题讨论】:

    标签: hapijs bookshelf.js


    【解决方案1】:

    我现在无法测试,但模型定义中对 require() 的调用对我来说看起来很奇怪......我会写的

    author: function() {
      return this.belongsTo(Author);
    }
    

    books: function(){
      return this.hasMany(Book, 'author_id');
    }
    

    PS。由于我无法立即进行测试,因此我想对此发表评论,但我没有足够的声誉......

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-18
      • 1970-01-01
      • 1970-01-01
      • 2018-04-04
      相关资源
      最近更新 更多