【问题标题】:Adonis 5 pagination ignoring data created from queries in hooksAdonis 5 分页忽略从钩子中的查询创建的数据
【发布时间】:2021-04-12 17:58:47
【问题描述】:

我正在尝试使用钩子创建软删除功能...类似于documentation 中的示例。这很好用。

我的问题是控制器中使用的分页没有检测到 @beforeFetch() 钩子中使用的任何查询更改并返回总记录(已删除和活动)。所以分页元数据保持不变,即使添加了钩子并且数据不同。我确实注意到 @beforePaginate() 挂钩存在,但它没有按预期工作,并且没有关于此的文档。

如何更新分页?

产品型号:

 @beforeFetch()
  public static softDeletesFetch = (query: ModelQueryBuilderContract<typeof Product>) => {
    query.whereNull('deleted_at')
  }

产品控制器:

  public async index({ request }) {

    const publicProductColumns = [
      'id',
      'categoryId',
      'name',
      'summary',
      'productCode',
      'manufacturer',
      'price'
    ]

    const currentPage = request.input('current_page', 1)
    const perPage = request.input('per_page', 20)
    const products = Product.query()

    products
      .select(publicProductColumns)
      //other stuff omited for clarity
 
    return await products.paginate(currentPage, perPage)
  }

输出:

 "meta": {
        "total": 369, //<---This stays same
        "per_page": 20,
        "current_page": 1,
        "last_page": 19,
        "first_page": 1,
        "first_page_url": "/?page=1",
        "last_page_url": "/?page=19",
        "next_page_url": "/?page=2",
        "previous_page_url": null
    },

【问题讨论】:

    标签: typescript adonis.js


    【解决方案1】:

    我找到的解决方案是使用 Scopes insted of hooks,例如

    @beforeFetch()
          public static softDeletesFetch = (query: ModelQueryBuilderContract<typeof Product>) => {
            query.whereNull('deleted_at')
          }
    

    会变成

    public static softDelete = scope((query) => {
        query.whereNull('deleted_at')
      });
    

    并像这样使用

        const products = Product.query().withScopes(scope => scope.softDelete())
    

    【讨论】:

      猜你喜欢
      • 2016-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-25
      • 2016-11-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多