使用bookshelf.js多态关系进行反向关系查找

时间:2016-03-14 20:44:09

标签: javascript node.js orm bookshelf.js

我使用多态关系允许Account与两种不同的用户类型相关联:CustomerStaff。我的模型定义如下:

var Customer = bookshelf.Model.extend({
  tableName: 'customer',
  accounts: function() {
    return this.morphMany(Account, 'concernable');
  }
});

var Staff = bookshelf.Model.extend({
  tableName: 'staff',
  accounts: function() {
    return this.morphMany(Account, 'concernable');
  }
});

var Account = bookshelf.Model.extend({
  tableName: 'account',
  concernable: function () {
    return this.morphTo('concernable', 'Staff', 'Customer');
  }
});

我的数据库是Postgres,我用于Account表的架构是:

id (int)
business_id (int)
concernable_id (int)
concernable_type (string)

我尝试做的是获取属于特定商家的所有帐户,并返回与这些帐户关联的客户。它与我在Bookshelf示例中看到的标准关系查找相反。这是我尝试过没有运气的事情:

   Account.where({
      business_id: filter.businessId,
      concernable_type: 'customer'
    })
    .fetchAll({
      withRelated: ['concernable']
    })
    .then((response) => {
      return reply.jsonapi(response, 'customer');
    });

我收到以下错误:The target polymorphic model was not found。如果我将withRelated更改为customer,那么错误就是customer is not found on the model

我试图做的是什么?

谢谢!

0 个答案:

没有答案