简体   繁体   English

如何根据联接表的列对Bookshelf.js查询的结果进行排序?

[英]How can I sort the results of a Bookshelf.js query based on a column of the join table?

I am trying to get the results from a Bookshelf.js query and sort them by a column from the join table. 我正在尝试从Bookshelf.js查询中获取结果,并通过联接表中的列对它们进行排序。 However, when adding 'withRelated', I am only able to get the target table and not the join table itself. 但是,当添加“ withRelated”时,我只能获取目标表,而不能获取联接表本身。 Below is the code that I have so far. 下面是我到目前为止的代码。

MyTable.forge().query({where: {id: req.params.id}})
  .fetch({
    withRelated: [
      {'children.children': (qb) => { qb.orderBy('position', 'asc'); }}
    ]
  }).then(result => {
    res.send(JSON.stringify({theResult: result}));
  });

The 'orderBy' is supposed to order by the column 'position' which is only in the join table. “ orderBy”应该按仅在联接表中的“位置”列进行排序。 It seems that 'qb' only returns results from the target table and not the join table. 看来“ qb”仅返回目标表的结果,而不返回联接表的结果。 I have attempted 'withPivot' but am not getting the correct result. 我已经尝试过“ withPivot”,但没有得到正确的结果。

So after looking through the returned object and reading through some more documentation I found that the attribute to orderBy is changed by Bookshelf.js to '_pivot_position'. 因此,在浏览了返回的对象并阅读了更多文档之后,我发现Bookshelf.js将orderBy的属性更改为“ _pivot_position”。 ' pivot ' is added to the column name and that is what you want to use. 将“ pivot ”添加到列名称,这就是您要使用的名称。 However, this only seems to work for the following. 但是,这似乎仅适用于以下情况。

withRelated: [
      {'children': (qb) => { qb.orderBy('_pivot_position', 'asc'); }}
    ]

As shown above, I had to exclude 'children.children' and just use 'children'. 如上所示,我必须排除“ children.children”,而仅使用“ children”。 I now wonder if Bookshelf.js allows you to specify multiple 'orderBy' columns from child elements. 我现在想知道Bookshelf.js是否允许您从子元素中指定多个“ orderBy”列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM