Bookshelf.js 访问多个相关的表

Bookshelf.js accessing multiple tables that are related

我正在处理三个 tables。

现在我可以获得用户的 feed (activities table) 和 activityTypes 对象 (id,type from activitytypes table),但我还需要获取给定 activity 的 related_user (users table) 对象,所以我会知道 [=36] 的详细信息=] 如果该列不为空。

用户

id
email
username
password_hash

activity类型

id
type

活动

id
user_id (foreign key from users, owner of the activity)
status
activitytype_id (foreign key from activitytypes)
related_user (foreign key from users. 
Shows relation with the user_id, if there's any. 
if activitytype_id is 2 or 3, this will be shown as "followed, "commented", etc.)

我的模型

var activityType = db.Model.extend({
  tableName: 'activitytypes',
  hasTimestamps: false
});

var activity = db.Model.extend({
  tableName: 'activities',
  hasTimestamps: true,

  activityTypes: function() {
    return this.belongsTo(activityType);
  }
});

var user = db.Model.extend({
  tableName: 'users',
  hasTimestamps: true,
    feed: function() {
    return this.hasMany(activity);
  }
});

这是我现有的查询,如何向其中添加 related_user 对象?

user.where({id : 43}).fetchAll({withRelated : ['feed.activityTypes']}).then(function(data) {
    data = data.toJSON();
    res.send(data);
  });

我解决了

我向 activity 添加了一个新方法,如下所示。

userRelated : function() {
    return this.belongsTo(user,'related_user');
  }

这是更新后的查询。不知道这样的优化方式对不对,但是确实有效

user.where({
    id: 43
  }).fetchAll({
    withRelated: ['feed.userRelated', 'feed.activityTypes']
  }).then(function(data) {
    data = data.toJSON();
    res.send(data);
  });

现在 feed、userRelated 和 activityTypes return 没问题,所有内容都在 data JSON 格式中。