簡體   English   中英

bookshelf.js未加載關系

[英]bookshelf.js not loading relation

我是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());
}); 

嘗試將{idAttribute:'UserId'}添加到您的用戶模型中,我發現我對FieldNames區分大小寫,因此'userid'導致沒有返回數據,但'UserId'導致了返回數據。 因此,請確保它與您數據庫中的字段匹配

因此,將模型更改為

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

並嘗試查詢,如uglycode的答案所示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM