我是书架上的新手,我想使用其他表中的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
问:如何通过书架查询特定用户的日志.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'} 添加到您的用户模型中我发现我的对字段名称区分大小写,因此"userid"没有返回数据,但"UserId"确实返回了。因此,请确保它与数据库中的字段匹配
因此,请将您的模型更改为
User = bookshelf.Model.extend({
tableName:'user',
idAttribute: 'userid',
logs: function() {
return this.hasMany(Log);
}
});
并尝试查询,如丑陋代码的答案所示