【问题标题】:Add data to collection before pagination in Laravel在 Laravel 中分页之前将数据添加到集合中
【发布时间】:2019-11-01 07:41:21
【问题描述】:

我从数据库中获取一些数据并通过以下调用进行分页:

$itemsList = DB::Table('items')->paginate(10);

数据中的每个项目都有一个与之关联的到期日期,我从中计算剩余天数并使用我编写的函数作为数组返回。我需要以某种方式将此数组集成到分页调用中,以便每个页面显示正确的剩余天数值。目前,我的刀片文件中有这样的内容:

<?php
$i = 0;
?>
@foreach ($itemsList as $item)
    <tr>
        <td>{{ $item->item_name }}</td>
        <td>{{ $item->item_user }}</td>
        <td>{{$left_days[$i++]}}</td>

使用此方法,第一页分页工作正常,left_days 数组引用列表中的正确项目。然而,在其他页面上,left_days 值指的是第一页的项目,因为每次运行的 i 值都从 0 开始。

我想我需要在分页调用之前将 left_days 数组添加到集合中,但我无法弄清楚如何。

更具体地说,下面是 $itemList 上 dd 的结果:

LengthAwarePaginator {#292 ▼
  #total: 94
  #lastPage: 10
  #items: Collection {#277 ▼
    #items: array:10 [▼
      0 => {#276 ▼
        +"id": 1
        +"item_name": "sadasd"
        +"item_user": "sadas"
        +"expiry_date": "2019-06-26"
        +"last_modified_by": "someone"
        +"created_at": "2019-06-18 15:19:33"
        +"updated_at": "2019-06-18 15:19:33"
      }
      1 => {#270 ▶}
      2 => {#279 ▶}
      3 => {#280 ▶}
      4 => {#281 ▶}
      5 => {#282 ▶}
      6 => {#283 ▶}
      7 => {#284 ▶}
      8 => {#285 ▶}
      9 => {#286 ▶}
    ]
  }
  #perPage: 10
  #currentPage: 1
  #path: "http://localhost:8000/licenses"
  #query: []
  #fragment: null
  #pageName: "page"
  +onEachSide: 3
  #options: array:2 [▶]
}

我认为我需要的是有一种方法可以在正确的位置插入我的数组,这样集合中的每个项目也有一个在分页之前计算的归档 left_days。

【问题讨论】:

  • {{ $item-&gt;left_days }} 怎么样,然后在您的模型中添加方法 public function getLeftDaysAttribute() { return 5; }
  • @RolandStarke 这只有在他们使用Item 模型时才有效;使用DB::table("items") 生成stdClass 对象,这些对象不能像模型那样应用函数。但是如果他们使用Item::paginate(10);,并且Item模型存在该功能,那么它就没有问题。
  • @TimLewis 我用Item::paginate(10); 调用了分页,这似乎有效。不过,我还没有在任何地方设置 left_days 变量。这是如何工作的?
  • 这就是模型的get{...}Attribute()函数的魔力。它将{...}(在本例中为{LeftDays})中的任何内容转换为可访问的属性。
  • 很酷。现在我需要弄清楚如何访问这个 getLeftDaysAttribute 函数中的 expiry_date 变量,以便进行计算。

标签: php html laravel pagination


【解决方案1】:

Roland Starke 和 Tim Lewis 给出的答案:

用途:

Item::paginate(10);

代替:

DB::Table('items')->paginate(10);'

并在模型中编写一个 get 函数,如下所示:

public function getLeftDaysAttribute(){
     calculations...
    return value;
}

之后我可以简单地在刀片文件中调用 left_days 的值:

 $item->left_days

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-06
    • 1970-01-01
    • 2017-04-23
    • 1970-01-01
    • 2020-02-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多