laravel集合中select()和only()的区别

问题描述 投票:0回答:1

我很想知道 Laravel 集合中 selectonly 方法有什么区别。 根据文档中的示例,它们都做了相同的事情

在 select 方法的文档中,我们有这样的内容:

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

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

\*
[
['name' => 'Taylor Otwell', 'role' => 'Developer'],
['name' => 'Victoria Faith', 'role' => 'Researcher'],
],
*/

仅适用于:

$collection = collect([
'product_id' => 1,
'name' => 'Desk',
'price' => 100,
'discount' => false
]);

$filtered = $collection->only(['product_id', 'name']);

$filtered->all();

// ['product_id' => 1, 'name' => 'Desk']
laravel laravel-10 laravel-collection laravel-11
1个回答
0
投票

在 Laravel 的 Collection 类中,

select()
only()
是用于根据特定键或条件从集合中检索项目子集的方法。

  • select()
    方法指定应从数据库中选择哪些列。这 方法是查询生成器的一部分,通常在您需要时使用 限制从数据库检索的列以改进 性能并减少传输的数据量。

  • only()
    方法仅检索具有指定键的项目 收藏。当您有一个集合时,这特别有用 数据,并且您想要过滤它以仅包含特定键。

主要区别:

select()
用于从数据库中查询特定列,而
only()
用于按键过滤集合。

© www.soinside.com 2019 - 2024. All rights reserved.