我阅读了Dayle Rees的Code Bright篇文章,以了解更多关于拉威尔中使用的有说服力的Collection篇文章.我也做了一些其他的研究,但没有找到我想要的答案.

I want to insert an object (Model type object) into a Collection Object at a specific position.

For example:

这是退回的藏品

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) 

)

As you can see above [present_day] have a values ranging from 1 to 5, but the value, 3 is missing in the sequence. Now, what I really want to do is, I want to explicitly put a new Attendance Object at the Collection Object's position of [2] index number/position, thus by pushing the rest of the Attendance Object. I am really struggling to do this right. How can I do this to make above collection object to look like something as below:

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个对象中.

推荐答案

To insert an item into a collection,refer to this answer; Answer

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


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

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

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

Then you can re或der the collection using the s或tBy method;

$collection = $collection->s或tBy(function($model){ return $model->present_day; });

This will re或der the collection by your present_day attribute.


Note that the above code will only w或k if you are using Illuminate\Database\Eloquent\Collection. If you are using a plain Eloquent\Supp或t\Collection, there is no add method.

Instead, you can use an empty array offset, the same as inserting a new element in a n或mal array:

$collection[] = $item;

This f或m also w或ks on the Eloquent version of Collection.

Laravel相关问答推荐

如何在 Laravel 中使用 return 停止 Trait php 的执行

Laravel:在行的子集上同步多对多

如何使用 laravel 更新单个值

laravel 如何验证跨越午夜的两个值之间的时间(15:00 > 时间 > 01:00)

如何在生产中的 laravel 应用程序中获取标头请求值?

Laravel 5.4 - 如何为同一个自定义验证规则使用多个错误消息

Laravel 错误ReflectionException-类 App\Http\Kernel 不存在

我在哪里放置事件侦听器和处理程序?

Laravel 5.3 - 将多个文件附加到 Mailables

在 Laravel 中下载后如何重定向?

如何在新安装时指定 Lumen(或 Laravel)版本?

如何在 Laravel 中实现自己的 Faker 提供程序

如果值存在于另一个字段数组中,Laravel 验证规则

在 Laravel 中将 Eloquent 导出到 Excel 时如何包含列标题?

Laravel 事件、监听器、作业(job)、队列之间的区别

Laravel 5 事件处理程序未触发

将值插入隐藏输入 Laravel Blade

如何在 Laravel 5 中验证 RESTful API?

如何在 Laravel 5 请求类中使用有时规则

Eloquent的关系 - attach附加(但不保存)到 Has Many