withRelated绑定未定义

时间:2015-09-09 14:40:35

标签: bookshelf.js

我有两种模式:

    var Book = bookshelf.Model.extend({
        tableName: 'books',
        chapters: function(){
            var chapters = require('./chapter').Chapter;
            return this.hasMany(chapters, 'bookId');
        }
    });

    module.exports = {
        Book: Book
    };

var Chapter = bookshelf.Model.extend({
    tableName: 'chapters',
    hasTimestamps: ['dateCreated', 'dateUpdated'],

    //relationship
    book: function(){
        var book = require('./user').Book;
        return this.belongsTo(book, 'bookId');
    }
});

module.exports = {
    Chapter: Chapter
}

我在其中一个控制器中执行此操作:

new Book.Book()
                .fetch({withRelated:['chapters']})
                .then(function(books){
                    resolve(books);
                }).catch(function(err){
                    reject(err);
                });

"章节":[]因为调试日志给我这个,绑定是未定义的:

{ method: 'select',
  options: {},
  bindings: [ 1 ],
  sql: 'select `books`.* from `books` limit ?' }
{ method: 'select',
  options: {},
  bindings: [ undefined ],
  sql: 'select `chapters`.* from `chapters` where `chapters`.`bookId` in (?)' }

2 个答案:

答案 0 :(得分:2)

Bookshelf假设您有一个名为' id'的列。在每个表中唯一标识每一行。如果您使用的是未被调用的主键' id'您需要指定所谓的能够在关系中使用模型的内容。这是由'idAttribute'完成的。会员,例如

var ModelA = bookshelf.Model.extend({
  tableName: "ModelA",
  idAttribute: "modelA_id"
  ...
}

});

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

答案 1 :(得分:0)

使用指定的idAttribute: 'cardId'解决了这个问题。