【问题标题】:Laravel 4.1 API Pagination - Create a custom JSON responseLaravel 4.1 API 分页 - 创建自定义 JSON 响应
【发布时间】:2014-07-04 17:59:25
【问题描述】:

我想知道是否可以在简单查询的分页结果中自定义返回对象的顺序。现在的响应顺序是分页信息,后跟包含我搜索过的模型的“数据”对象。我想知道是否可以颠倒顺序,使其产品信息后跟某种分页对象。

我的查询是:

return Product::paginate(100);

我的结果是:

{"total":466,"per_page":100,"current_page":1,"last_page":5,"from":1,"to":100,"data":[{"id":28,"account_id":5,"created_by_id":14,"type":"accessory","title":"Product #28","description":"D","max_per_order":1,"stock":3565,"created_at":"1998-04-18 00:00:00","updated_at":"1994-10-28 00:00:00","deleted_at":null},{"id":44,"account_id":5,"created_by_id":36,"type":"registration","title":"Product #44","description":"Z","max_per_order":10,"stock":13739,"created_at":"2014-04-20 00:00:00","updated_at":"1991-06-03 00:00:00","deleted_at":null}]}

我希望结果是这样的:

[products: [{"id":28,"account_id":5,"created_by_id":14,"type":"accessory","title":"Product #28","description":"D","max_per_order":1,"stock":3565,"created_at":"1998-04-18 00:00:00","updated_at":"1994-10-28 00:00:00","deleted_at":null},{"id":44,"account_id":5,"created_by_id":36,"type":"registration","title":"Product #44","description":"Z","max_per_order":10,"stock":13739,"created_at":"2014-04-20 00:00:00","updated_at":"1991-06-03 00:00:00","deleted_at":null},{"id":57,"account_id":5,"created_by_id":40,"type":"accessory","title":"Product #57","description":"Z","max_per_order":4,"stock":19376,"created_at":"1970-03-27 00:00:00","updated_at":"2001-01-01 00:00:00","deleted_at":null}], pagination: {"total":466,"per_page":100,"current_page":1,"last_page":5,"from":1,"to":100}]

我将如何去做这样的事情?自己写分页代码会不会更方便?

【问题讨论】:

    标签: json laravel pagination


    【解决方案1】:

    没有办法使用 laravel 特定的措施来做到这一点,它需要你实际抓取数据并创建自己的自定义数组以作为 JSON 返回。不过,这很简单,我在下面添加了一个示例。

    $products = Product::paginate(100);
    $response = [
        'products'   => $products->getItems()->toArray(),
        'pagination' => [
            'total'        => $products->getTotal(),
            'per_page'     => $products->getPerPage(),
            'current_page' => $products->getCurrentPage(),
            'last_page'    => $products->getLastPage(),
            'from'         => $products->getFrom(),
            'to'           => $products->getTo()
        ]
    ];
    
    return Response::json($response);
    

    我最近用 laravel 创建了几个 API,我面临的一个问题是在保持统一响应的同时对数据进行分页,这就是我的处理方式。

    希望对你有帮助。

    【讨论】:

    • 这是你的 PHP 版本,[] 是 php 5.4+ iirc 中数组的简写。
    • 那我不认为你使用的是 5.5,afaik,它没有配置选项。
    • @Irfan 在第二页,因此,在同一页上,但 ?page=2
    【解决方案2】:

    Laravel 已经包含了这个功能,试试这个

    $products = Product::paginate(100)->toJson();
    return $products
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-22
      • 1970-01-01
      • 1970-01-01
      • 2019-03-04
      • 2019-04-08
      • 2018-02-28
      • 2018-06-17
      • 1970-01-01
      相关资源
      最近更新 更多