【发布时间】: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