bookshelf js中的多个连接



我试图使一个api的商店使用书架作为我的ORM。为了使事情平静,我希望我的路径看起来像这样。/男人/夹克的我的数据是结构化的,所以要做到这一点,我必须找到类别(男性/女性),所以我可以得到它的相关部分(夹克,牛仔裤,帽子等),然后得到该部分的相关产品。数据是这样的,有两个名称为jacket的section行,但是其中一个a有一个fk,将类别链接到1(make),另一个链接到2(female)。

我在文档中发现了这一点,但它不会起作用(我猜)你只能在第一个相关返回单个实体时链接相关,在这种情况下,我的类别有许多部分。

new Photo({id: 1}).fetch({
   withRelated: ['account']
  }).then(function(photo) {
   if (photo) {
  var account = photo.related('account');
  if (account.id) {
   return account.related('trips').fetch();
  }
 }
  });

在raw sql中,我的查询看起来像这样

SELECT * FROM sections
JOIN categories ON categories.id = sections.category_id
JOIN products ON products.section_id = sections.id
where categories.name = 'mens' AND sections.name = 'jackets';

您可以直接使用帐户获取行程,例如:

new Photo({id: 1}).fetch({
  withRelated: [
   { 'account': qb => qb.where(needed conditions) },
   'account.trips',
  ]
}).then(function(photo) {
    YOUR CODE
});

现在你只需要检查.related('account').related('account').related('trips')在使用它们之前是否为空

我希望这对你有帮助。

创建Sections模型后,您可以使用如下查询:

Sections.query(qb => {
qb.leftJoin('categories', 'sections.category_id', 'categories.id);
qb.leftJoin('products', 'sections.id', 'products.section_id);
qb.where('categories.name', 'men');
qb.andWhere('sections.name', 'jackets');
}.fetchOne({withRelated: 'products'});

最新更新