我是bookshelfjs的新手,我想使用其他表中的ID从其他表中获取数据。
我正在使用以下示例数据:

/* User's Table */
----------------+-------------------+----------
   lastname     |    firstname      |   id
----------------+-------------------+---------
Dela Cruz          Juan                1
Pendoku            Pedro               2

/* Logs's Table */
----------------+--------------+----------
     userid     |    time      |   id
----------------+--------------+---------
  1                 8:00           1
  2                12:00           2
  1                 9:00           3


问题:如何通过bookshelf.js查询特定用户的日志?

所以结果应该是这样的:

----------------+--------------+----------
     lastname   |    time      |   id
----------------+--------------+---------
 Dela Cruz          8:00           1
 Dela Cruz          9:00           3


我的查询:

new User({'lastname': 'Dela Cruz'})
  .logs()
  .fetch()
  .then(function(timelog) {
    console.log(timelog.toJSON());
});


我的模特

var User, Log;

User = bookshelf.Model.extend({
  tableName:'user',
  logs: function() {
     return this.hasMany(Log, 'userid');
  }
});

Log = bookshelf.Model.extend({
  tableName:'log',
  user: function(){
    return this.belongsTo(User, 'userid');
  }
});


记录错误:

{ __cid: '__cid1',
  method: 'select',
  options: undefined,
  bindings: [undefined],
  sql: 'select log.* from log where log.userid = ?'
}

最佳答案

将用户模型更改为此:

User = bookshelf.Model.extend({
  tableName:'user',
  logs: function() {
     return this.hasMany(Log);
  }
});


尝试一下

new User({'lastname': 'Dela Cruz'})
  .fetch({withRelated:['logs']})
  .then(function(timelog) {
    console.log(timelog.toJSON());
});

关于javascript - bookshelf.js未加载关系,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29641335/

10-09 22:24