大学网 > php中文网 > 每日编程理解 Laravel 11 中 pluck() 和 select() 之间的区别正文

理解 Laravel 11 中 pluck() 和 select() 之间的区别

中国大学网 2024-10-17

Laravel 是最流行的 php 框架之一,提供了一系列强大的数据操作方法。其中,pluck() 和 select() 在处理集合时经常使用。尽管它们看起来相似,但它们的目的不同。在本文中,我们将探讨这两种方法之间的差异,解释何时使用每种方法,并提供实际的编码示例来演示它们在 laravel 11 中的用法。

什么是 pluck()?

pluck() 方法旨在从集合中的单个键中提取值。当您想要从数组或对象集合中检索特定属性时,它特别方便。

pluck() 的示例

假设您有一系列产品,并且您只想提取产品名称:

$collection = collect([
    ['product_id' => 'prod-100', 'name' => 'desk'],
    ['product_id' => 'prod-200', 'name' => 'chair'],
]);

// pluck only the names of the products
$plucked = $collection->pluck('name');

$plucked->all();
// output: ['desk', 'chair']

此外,您可以使用 pluck() 将自定义键分配给结果集合:

$plucked = $collection->pluck('name', 'product_id');

$plucked->all();
// output: ['prod-100' => 'desk', 'prod-200' => 'chair']

使用 pluck() 嵌套值

pluck() 方法还支持使用点表示法提取嵌套值:

$collection = collect([
    [
        'name' => 'laracon',
        'speakers' => [
            'first_day' => ['rosa', 'judith'],
        ],
    ],
    [
        'name' => 'vueconf',
        'speakers' => [
            'first_day' => ['abigail', 'joey'],
        ],
    ],
]);

$plucked = $collection->pluck('speakers.first_day');

$plucked->all();
// output: [['rosa', 'judith'], ['abigail', 'joey']]

处理重复项

处理具有重复键的集合时,pluck() 将使用与每个键关联的最后一个值:

$collection = collect([
    ['brand' => 'tesla',  'color' => 'red'],
    ['brand' => 'pagani', 'color' => 'white'],
    ['brand' => 'tesla',  'color' => 'black'],
    ['brand' => 'pagani', 'color' => 'orange'],
]);

$plucked = $collection->pluck('color', 'brand');

$plucked->all();
// output: ['tesla' => 'black', 'pagani' => 'orange']

什么是选择()?

laravel 中的 select() 方法更类似于 SQL 的 select 语句,允许您从集合中选择多个键,并仅返回这些键作为新集合。

select() 的示例

让我们考虑一个您想要检索名称和角色的用户集合:

$users = collect([
    ['name' => 'Taylor Otwell', 'role' => 'Developer', 'status' => 'active'],
    ['name' => 'Victoria Faith', 'role' => 'Researcher', 'status' => 'active'],
]);

$selectedUsers = $users->select(['name', 'role']);

$selectedUsers->all();
// Output: [
//     ['name' => 'Taylor Otwell', 'role' => 'Developer'],
//     ['name' => 'Victoria Faith', 'role' => 'Researcher'],
// ]

使用 select(),可以一次性从集合中拉取多个属性。

pluck() 和 select() 之间的主要区别

  • 目的

    • pluck() 用于从集合中提取单个属性或键值对。
    • select() 用于从集合中的每个项目中检索多个属性,类似于 sql 查询。
  • 返回结构:

    • 当提供第二个键时,pluck() 返回值的平面数组或关联数组。
    • select() 返回仅包含指定键的数组集合。
  • 用法

    • 当您需要特定键的值列表时,请使用 pluck()。
    • 当您需要集合中每个元素的多个字段时,请使用 select()。

何时使用哪个?

  • :

    时使用 pluck()
    • 您需要从单个键中提取值。
    • 您正在处理嵌套数据并想要检索特定的嵌套属性。
  • :

    时使用 select()
    • 您需要检索多个键或属性。
    • 您想要重组数据以专注于某些字段。

结论

在 laravel 11 中,pluck() 和 select() 都提供了灵活的方法来操作集合。 pluck() 简化了提取单个属性的过程,而 select() 在需要处理多个属性时为您提供了更多控制权。了解这两种方法之间的差异可以让您优化数据操作流程并编写更清晰、更高效的代码。

通过掌握 pluck() 和 select(),您可以在 laravel 应用程序中轻松处理复杂的数据结构。快乐编码!

以上就是理解 Laravel 11 中 pluck() 和 select() 之间的区别的详细内容,更多请关注中国大学网其它相关文章!