我读过戴尔·里斯的代码明亮 https://daylerees.com/codebright/了解更多关于雄辩的信息Collection
在 Laravel 中使用。还做了一些其他研究,但找不到我正在寻找的答案。
我想插入一个对象(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
序列中缺失。现在,我真正想做的是,我想明确地放置一个新的Attendance Object
在集合对象的位置[2]
索引号/位置,从而通过推送考勤对象的其余部分。我真的很难正确地做到这一点。我怎样才能使上面的集合对象看起来像下面这样:
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
,我不知道该怎么做。
Note:我不想将其转换为数组并在数组中进行插入。出于某种原因,我想将此输出严格限制在Collection
object.
要将项目插入集合中,请参阅此答案;Answer https://stackoverflow.com/questions/27733020/how-can-i-add-an-item-into-a-laravel-eloquent-collection-by-index
基本上,拆分集合,在相关索引处添加项目。
您可以将该项目添加到Eloquent\Collection
对象与add
方法;
$collection->add($item); // Laravel 4
or
$collection->push($item); // Laravel 5
然后您可以使用以下命令对集合重新排序sortBy
method;
$collection = $collection->sortBy(function($model){ return $model->present_day; });
这将按您的顺序重新排序集合present_day
属性。
请注意,上述代码仅在您使用时才有效Illuminate\Database\Eloquent\Collection
。如果您使用的是普通Eloquent\Support\Collection
,没有add
method.
相反,您可以使用空数组偏移量,与在普通数组中插入新元素相同:
$collection[] = $item;
这种形式也适用于 Eloquent 版本Collection
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)