Eloquent: 集合

Laravel 中文文档 · 2019-01-15 22:11:24

简介

Eloquent 返回的所有多结果集都是 Illuminate\Database\Eloquent\Collection 对象的实例,包括通过 get 方法检索或通过访问关联关系获取到的结果。 Eloquent 的集合对象继承了 Laravel 的 集合基类 ,因此它自然也继承了数十种能优雅地处理 Eloquent 模型底层数组的方法。

当然,所有的集合都可以作为迭代器,你可以像遍历简单的 PHP 数组一样来遍历它们:

$users = App\User::where('active', 1)->get();

foreach ($users as $user) {
    echo $user->name;
}

不过,集合比数组更加强大,它通过更直观的接口暴露出可链式调用的 map/reduce 等操作。例如,让我们移除所有未激活的用户并收集剩余用户的名字:

$users = App\User::all();

$names = $users->reject(function ($user) {
    return $user->active === false;
})
->map(function ($user) {
    return $user->name;
});

{note} 大多数 Eloquent 集合方法会返回新的 Eloquent 集合实例,但是 pluckkeyszipcollapseflattenflip 方法除外,它们会返回一个 集合基类 实例。同样,结果 map 操作返回的集合不包括任何 Eloquent 模型,那么它会被自动转换成集合基类。

可用的方法

集合基类

所有 Eloquent 都继承了基础的 Laravel 集合 对象;因此,它们也继承了所有集合基类提供的强大的方法:

自定义集合

如果你需要在自己的扩展方法中使用自定义的 Collection 对象,你可以在你的模型中重写 newCollection方法:

<?php

namespace App;

use App\CustomCollection;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * 创建一个新的 Eloquent 集合实例对象。
     *
     * @param  array  $models
     * @return \Illuminate\Database\Eloquent\Collection
     */
    public function newCollection(array $models = [])
    {
        return new CustomCollection($models);
    }
}

一旦你定义了 newCollection 方法,任何时候都可以在 Eloquent 返回的模型的 Collection 实例中获得你的自定义集合实例。如果你想要在应用程序的每个模型中使用同一个自定义集合,则应该在所有的模型继承的模型基类中重写 newCollection 方法。

点击查看所有 Laravel 中文文档 文章: https://www.codercto.com/courses/l/3.html

查看所有标签

Web Security Testing Cookbook

Web Security Testing Cookbook

Paco Hope、Ben Walther / O'Reilly Media / 2008-10-24 / USD 39.99

Among the tests you perform on web applications, security testing is perhaps the most important, yet it's often the most neglected. The recipes in the Web Security Testing Cookbook demonstrate how dev......一起来看看 《Web Security Testing Cookbook》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

URL 编码/解码
URL 编码/解码

URL 编码/解码

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具