【问题标题】:Strapi - How to GET data sorted based on relation property?Strapi - 如何获取基于关系属性排序的数据?
【发布时间】:2020-12-05 01:32:21
【问题描述】:

我有一个 Articles 表,它与 Authors 表有关系。每个作者都有一个名称属性。我想对文章发出 GET 请求并接收根据作者姓名排序的文章。

当我在 url 参数中使用 _sort=author 时,我会根据作者对象的 ID 对文章进行排序。

当我在 url 参数中使用 _sort=author.name 时,我会以看似随机的顺序获取文章,但绝对不是基于 author.name。

如何根据 author.name 对数据进行排序?

我使用 mongoDB 作为我的数据库。

【问题讨论】:

    标签: mongodb strapi


    【解决方案1】:

    这是_sort 的默认行为。但是,您可以简单地通过覆盖 api/article/services/article.js 中的 find 方法来按作者姓名排序,如下所示:

    module.exports = {
        async find(params, populate) {
            let result = await strapi.query('article').find(params, populate);
    
            if (params._sort == 'author')
                return result.sort((a, b) => (a.author.name > b.author.name) ? 1 : -1);
    
            return result;
        },
    }
    

    查看自定义服务的文档以获取更多信息:https://strapi.io/documentation/v3.x/concepts/services.html#concept

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多