[英]bookshelf.js not loading relation
Im new to bookshelfjs and i want to get the data from other table using the ID from other table. 我是bookshelfjs的新手,我想使用其他表中的ID从其他表中获取数据。 Im using this sample data:
我正在使用以下示例数据:
/* 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
Question: how i can query the logs of specific user thru bookshelf.js? 问题:如何通过bookshelf.js查询特定用户的日志?
so the result should be like this: 所以结果应该是这样的:
----------------+--------------+----------
lastname | time | id
----------------+--------------+---------
Dela Cruz 8:00 1
Dela Cruz 9:00 3
My query: 我的查询:
new User({'lastname': 'Dela Cruz'})
.logs()
.fetch()
.then(function(timelog) {
console.log(timelog.toJSON());
});
My models 我的模特
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');
}
});
Log Error: 记录错误:
{ __cid: '__cid1',
method: 'select',
options: undefined,
bindings: [undefined],
sql: 'select log.* from log where log.userid = ?'
}
Change the user model to this: 将用户模型更改为此:
User = bookshelf.Model.extend({
tableName:'user',
logs: function() {
return this.hasMany(Log);
}
});
And try this 尝试一下
new User({'lastname': 'Dela Cruz'})
.fetch({withRelated:['logs']})
.then(function(timelog) {
console.log(timelog.toJSON());
});
Try adding the {idAttribute: 'UserId'} to your User model I found mine was case sensitive to the FieldNames so 'userid' resulted in no returned data but 'UserId' did. 尝试将{idAttribute:'UserId'}添加到您的用户模型中,我发现我对FieldNames区分大小写,因此'userid'导致没有返回数据,但'UserId'导致了返回数据。 So make sure it matches the field in your db
因此,请确保它与您数据库中的字段匹配
So change your model to 因此,将模型更改为
User = bookshelf.Model.extend({
tableName:'user',
idAttribute: 'userid',
logs: function() {
return this.hasMany(Log);
}
});
And try the query as shown in uglycode's answer 并尝试查询,如uglycode的答案所示
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.