Laravel 5.3 - 将项目添加到分页器数据?

时间:2017-04-19 21:44:21

标签: laravel laravel-5 laravel-5.3

我已经返回了这个paginator实例:

$products =
{
  "products": 3,
  "per_page": 10,
  "current_page": 1,
  "data": [
    {
      "id": 4,
      "product_type": "electronic",
      "product_id": 6
    },
    {
      "id": 6,
      "type": "electronic",
      "product_id": 5
    },
    {
      "id": 9,
      "type": "kitchen",
      "product_id": 4
    }
  ]
}

我正在尝试将项目添加为data键的第一项,如下所示:

$firstItem = {
  "item": "should be first in data",
  "code": 12345
}

最终结果应如下所示:

$products =
{
  "products": 3,
  "per_page": 10,
  "current_page": 1,
  "data": [
    {                                    <-
      "item": "should be first in data", <-
      "code": 12345                      <-
    },                                   <-
    {
      "id": 4,
      "product_type": "electronic",
      "product_id": 6
    },
    {
      "id": 6,
      "type": "electronic",
      "product_id": 5
    },
    {
      "id": 9,
      "type": "kitchen",
      "product_id": 4
    }
  ]
}

我尝试了很多方法,但没有人得到结果。 知道如何完成最终结果吗?

1 个答案:

答案 0 :(得分:1)

如果$products中有一个分页结果的实例,那么您可以使用类似下面的内容将新项目添加到数据中,例如:

// Get the paginated data
$products = \App\Product::paginate(10);

// Create a new item and populate
$item = new \StdClass;
$item->item = "should be first in data";
$item->code = 12345;

// Insert the new item at top
$products->prepend($item);

就是这样。新StdClass(非擅长模型)项目将位于顶部。