Laravel Laravel

以下是翻译后的版本:

  • 序章

    • 发布说明
    • 升级指南
    • 贡献指南
  • 快速开始

    • 安装
    • 配置
    • 目录结构
    • 前端
    • 入门套件
    • 部署
  • 架构概念

    • 请求生命周期
    • 服务容器
    • 服务提供者
    • 门面
  • 基础

    • 路由
    • 中间件
    • CSRF 保护
    • 控制器
    • 请求
    • 响应
    • 视图
    • Blade 模板
    • 资源打包
    • URL 生成
    • 会话
    • 验证
    • 错误处理
    • 日志记录
  • 深入探讨

    • Artisan 控制台
    • 广播
    • 缓存
    • 集合
    • 并发
    • 上下文
    • 契约
    • 事件
    • 文件存储
    • 辅助函数
    • HTTP 客户端
    • 本地化
    • 邮件
    • 通知
    • 包开发
    • 进程
    • 队列
    • 速率限制
    • 字符串
    • 任务调度
  • 安全

    • 认证
    • 授权
    • 邮件验证
    • 加密
    • 哈希
    • 密码重置
  • 数据库

    • 快速开始
    • 查询构建器
    • 分页
    • 迁移
    • 数据填充
    • Redis
    • MongoDB
  • Eloquent ORM

    • 快速开始
    • 关系
    • 集合
    • 变换器/类型转换
    • API 资源
    • 序列化
    • 工厂
  • 测试

    • 快速开始
    • HTTP 测试
    • 控制台测试
    • 浏览器测试
    • 数据库测试
    • Mock 测试
  • 软件包

    • Breeze
    • Cashier(Stripe)
    • Cashier(Paddle)
    • Dusk
    • Envoy
    • Fortify
    • Folio
    • Homestead
    • Horizon
    • Jetstream
    • Mix
    • Octane
    • Passport
    • Pennant
    • Pint
    • Precognition
    • Prompts
    • Pulse
    • Reverb
    • Sail
    • Sanctum
    • Scout
    • Socialite
    • Telescope
    • Valet
  • API 文档
Icon

提示 您正在浏览旧版本的 Laravel 的文档. 请考虑将你的项目升级到 Laravel 11.x.

Eloquent 集合
10.x
10.x 9.x 8.5 8.x 7.x 6.x 5.8 5.7 5.6 5.5 5.4 5.3 5.2 5.1

Laravel 10 中文文档 /

未匹配的标注

Eloquent:集合

  • 介绍
  • 可用的方法
  • 自定义集合

介绍

所有以多个模型为查询结果的 Eloquent 方法的返回值都是 Illuminate\Database\Eloquent\Collection 类的实例, 其中包括了通过 get 方法和关联关系获取的结果。Eloquent 集合对象扩展了 Laravel 的基础集合类,因此它自然地继承了许多用于流畅地处理 Eloquent 模型的底层数组的方法。请务必查看 Laravel 集合文档以了解所有这些有用的方法!

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

use App\Models\User;

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

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

然而,正如前面所提到的,集合远比数组要强大,而且暴露了一系列直观的、可用于链式调用的 map/reduce 方法。打个比方,我们可以删除所有不活跃的模型,然后收集余下的所有用户的名字。

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

Eloquent 集合转换

在大多数 Eloquent 集合方法返回一个新的 Eloquent 集合实例的前提下,collapse,flatten,flip, keys,pluck,以及 zip 方法返回一个基础集合类的实例。 如果一个 map 方法返回了一个不包含任何模型的 Eloquent 集合,它也会被转换成一个基础集合实例。

可用的方法

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

另外, Illuminate\Database\Eloquent\Collection 类提供了一套上层的方法来帮你管理你的模型集合。大多数方法返回 Illuminate\Database\Eloquent\Collection 实例;然而,也会有一些方法, 例如 modelKeys, 它们会返回基于 Illuminate\Support\Collection 类的实例。

append
contains
diff
except
find
fresh
intersect
load
loadMissing
modelKeys
makeVisible
makeHidden
only
setVisible
setHidden
toQuery
unique

<code>append($attributes)</code> {.collection-method .first-collection-method}

可以使用append方法来为集合中的模型追加属性。 可以是数组或单个属性追加:

$users->append('team');

$users->append(['team', 'is_admin']);

<code>contains($key, $operator = null, $value = null)</code> {.collection-method}

contains 方法可用于判断集合中是否包含指定的模型实例。这个方法接收一个主键或者模型实例:

$users->contains(1);

$users->contains(User::find(1));

<code>diff($items)</code> {.collection-method}

diff 方法返回不在给定集合中的所有模型:

use App\Models\User;

$users = $users->diff(User::whereIn('id', [1, 2, 3])->get());

<code>except($keys)</code> {.collection-method}

except 方法返回给定主键外的所有模型:

$users = $users->except([1, 2, 3]);

<code>find($key)</code> {.collection-method}

find 方法查找给定主键的模型。如果 $key 是一个模型实例, find 将会尝试返回与主键匹配的模型。 如果 $key 是一个关联数组, find 将返回所有数组主键匹配的模型:

$users = User::all();

$user = $users->find(1);

<code>fresh($with = [])</code> {.collection-method}

fresh 方法用于从数据库中检索集合中每个模型的新实例。此外,还将加载任何指定的关联关系:

$users = $users->fresh();

$users = $users->fresh('comments');

<code>intersect($items)</code> {.collection-method}

intersect 方法返回给定集合与当前模型的交集:

use App\Models\User;

$users = $users->intersect(User::whereIn('id', [1, 2, 3])->get());

<code>load($relations)</code> {.collection-method}

load 方法为集合中的所有模型加载给定关联关系:

$users->load(['comments', 'posts']);

$users->load('comments.author');

$users->load(['comments', 'posts' => fn ($query) => $query->where('active', 1)]);

<code>loadMissing($relations)</code> {.collection-method}

如果尚未加载关联关系,则 loadMissing 方法将加载集合中所有模型的给定关联关系:

$users->loadMissing(['comments', 'posts']);

$users->loadMissing('comments.author');

$users->loadMissing(['comments', 'posts' => fn ($query) => $query->where('active', 1)]);

<code>modelKeys()</code> {.collection-method}

modelKeys 方法返回集合中所有模型的主键:

$users->modelKeys();

// [1, 2, 3, 4, 5]

<code>makeVisible($attributes)</code> {.collection-method}

makeVisible 方法使模型上的隐藏属性可见 :

$users = $users->makeVisible(['address', 'phone_number']);

<code>makeHidden($attributes)</code> {.collection-method}

makeHidden 方法隐藏模型属性 :

$users = $users->makeHidden(['address', 'phone_number']);

<code>only($keys)</code> {.collection-method}

only 方法返回具有给定主键的所有模型:

$users = $users->only([1, 2, 3]);

<code>setVisible($attributes)</code> {.collection-method}

setVisible方法临时覆盖集合中每个模型的所有可见属性:

$users = $users->setVisible(['id', 'name']);

<code>setHidden($attributes)</code> {.collection-method}

setHidden方法临时覆盖集合中每个模型的所有隐藏属性:

$users = $users->setHidden(['email', 'password', 'remember_token']);

<code>toQuery()</code> {.collection-method}

toQuery 方法返回一个 Eloquent 查询生成器实例,该实例包含集合模型主键上的 whereIn 约束:

use App\Models\User;

$users = User::where('status', 'VIP')->get();

$users->toQuery()->update([
    'status' => 'Administrator',
]);

<code>unique($key = null, $strict = false)</code> {.collection-method}

unique 方法返回集合中所有不重复的模型,若模型在集合中存在相同类型且相同主键的另一模型,该模型将被删除:

$users = $users->unique();

自定义集合

如果你想在与模型交互时使用一个自定义的 Collection 对象,你可以通过在模型中定义 newCollection 方法来实现:

<?php

namespace App\Models;

use App\Support\UserCollection;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * 创建新的Elquent Collection实例。
     *
     * @param  array<int, \Illuminate\Database\Eloquent\Model>  $models
     * @return \Illuminate\Database\Eloquent\Collection<int, \Illuminate\Database\Eloquent\Model>
     */
    public function newCollection(array $models = []): Collection
    {
        return new UserCollection($models);
    }
}

一旦在模型中定义了一个 newCollection 方法,每当 Eloquent 需要返回一个 Illuminate\Database\Eloquent\Collection 实例的时候,将会返回自定义集合的实例取代之。如果你想使每一个模型都使用自定义的集合,可以在一个模型基类中定义一个 newCollection 方法,然后让其它模型派生于此基类。

本文章首发在 网站上。



原文地址:/cndocs/10.x/el...

译文地址:/cndocs/10.x/el...

上一篇 下一篇

成为Laravel合作伙伴

Laravel Partners是提供一流Laravel开发和咨询服务的精英商店。我们每个合作伙伴都可以帮助您制定一个精美,结构完善的项目.

我们的伙伴
Laravel
亮点
  • Our Team
  • 发布说明
  • 入门
  • 路由
  • Blade 模板
  • 身份验证
  • 用户授权
  • Artisan 控制台
  • 数据库
  • Eloquent ORM
  • 测试
资源
  • Laravel Bootcamp
  • Laracasts
  • Laravel News
  • Laracon
  • Laracon EU
  • Laracon India
  • Jobs
  • Forums
  • Trademark
  • 版本发布时间
  • 包开发
  • 命令行应用
  • TALL stack全栈开发
  • Blade UI Kit
  • 前端资源构建
伙伴
  • WebReinvent
  • Vehikl
  • Tighten
  • 64 Robots
  • Active Logic
  • Byte 5
  • Curotec
  • Cyber-Duck
  • DevSquad
  • Jump24
  • Kirschbaum
生态系统
  • Cashier
  • Dusk
  • Echo
  • Envoyer
  • Forge
  • Horizon
  • Nova
  • Octane
  • Sail
  • Sanctum
  • Scout
  • Spark
  • Telescope
  • Valet
  • Vapor

Laravel是一个具有表达力,优雅语法的Web应用程序框架。我们认为,发展必须是一种令人愉悦的创造力,才能真正实现。Laravel试图通过减轻大多数Web项目中使用的常见任务来减轻开发的痛苦.

Laravel是Taylor Otwell的商标.
Copyright © 2011-2025 Laravel中文网 LLC.

  • Twitter
  • GitHub
  • Discord
Laravel 全栈开发网 推荐使用阿里云 按Ctrl+D试试