【问题标题】:How to insert an object (Model type object) into Collection Object in Laravel at specific index number?如何将对象(模型类型对象)插入到 Laravel 中特定索引号的集合对象中?
【发布时间】:2015-02-08 10:02:41
【问题描述】:

我已经阅读了 Dayle Rees 的 Code Bright 以了解更多关于 Laravel 中使用的 Eloquent Collections。也做了一些其他的研究,但找不到我想要的答案。

我想在特定位置插入一个对象(Model 类型对象)到 Collection 对象中。

例如:

这是返回的集合

Illuminate\Database\Eloquent\Collection Object
(
    [0] => Attendance Object
        ([present_day] => 1)

    [1] => Attendance Object
        ([present_day] => 2)

    [2] => Attendance Object
        ([present_day] => 4) 

    [3] => Attendance Object
        ([present_day] => 5) 

)

正如您在上面看到的,[present_day] 的值范围为 1 to 5,但序列中缺少值 3。现在,我真正想要做的是,我想在集合对象的[2] 索引号/位置的位置显式地放置一个新的Attendance Object,从而推动出勤对象的其余部分。我真的很难做到这一点。我怎样才能使上面的集合对象看起来像下面这样:

Illuminate\Database\Eloquent\Collection Object
(
    [0] => Attendance Object
        ([present_day] => 1)

    [1] => Attendance Object
        ([present_day] => 2)

    [2] => Attendance Object    // This is where new object was added.
        ([present_day] => 3) 

    [4] => Attendance Object
        ([present_day] => 4) 

    [5] => Attendance Object
        ([present_day] => 5) 

)

我认为如果它是数组的话,有一些方法可以做到这一点。由于这是Collection,我不知道该怎么做。

注意:我不想将它转换为数组并在数组中插入。出于某种原因,我希望将这个输出严格放在Collection 对象中。

【问题讨论】:

  • 集合对象有一个 add 方法,使用它然后像这样重新排序集合; $collection->sortBy(function($model){ return $model->present_day; }); 这会将集合重新排序为您想要的。
  • 我还没有尝试过解决方案。只需阅读您的评论,我相信它应该可以工作。实际上,这是解决我的问题的好方法。
  • @MattBurrow 我做到了。效果很好!!
  • 我会添加为答案。

标签: php laravel collections laravel-4 eloquent


【解决方案1】:

要将项目插入集合中,请参阅此答案; Answer

基本上,拆分集合,在相关索引处添加项目。


您可以使用add 方法将项目添加到Eloquent\Collection 对象;

$collection->add($item);  // Laravel 4

$collection->push($item); // Laravel 5 

然后您可以使用sortBy 方法对集合重新排序;

$collection = $collection->sortBy(function($model){ return $model->present_day; });

这将根据您的present_day 属性对集合重新排序。


请注意,上述代码仅在您使用Illuminate\Database\Eloquent\Collection 时有效。如果您使用的是普通的Eloquent\Support\Collection,则没有add 方法。

相反,您可以使用空数组偏移量,与在普通数组中插入新元素相同:

$collection[] = $item;

此表单也适用于 Eloquent 版本的 Collection

【讨论】:

  • 对于来到这里并想知道这不再起作用的每个人 [L5 和更高版本],请尝试 $collection->push($item);。它在集合末尾附加一个项目
  • 当没有提到“索引”时,我不确定为什么这是公认的答案
  • 值得一提的是,我们还有$collection->prepend()$collection->merge(),有时它们也很有用,因为只需collect() 创建一个新的Collection
【解决方案2】:

put 方法在集合中设置给定的键和值:

$collection = collect(['product_id' => 1, 'name' => 'Desk']);

$collection->put('price', 100);

$collection->all();

// ['product_id' => 1, 'name' => 'Desk', 'price' => 100]

【讨论】:

    【解决方案3】:

    假设你想在位置 4 输入一个收藏项

    $position = 4;
    
    $top = $collection->splice(0,$position);
    
    $bottom = $collection->splice($position);
    
    $top->push($newItem);
    
    $collection = $top->concat($bottom);
    

    【讨论】:

      猜你喜欢
      • 2012-11-20
      • 1970-01-01
      • 1970-01-01
      • 2013-07-28
      • 1970-01-01
      • 2016-01-20
      • 1970-01-01
      • 2020-03-02
      • 1970-01-01
      相关资源
      最近更新 更多