Laravel 中 pluck() 和 list() 的区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39101855/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 14:21:36  来源:igfitidea点击:

Difference between pluck() and lists() in laravel?

laraveleloquentlaravel-5.2

提问by Devashish Jaiswal

This is so confusing to me. I don't see any difference between these two methods. If I var_dump()the object returned by these methods, they are exactly the same but the book by Dayle Rees says that pluck()returns a single value from the given column (the first one) while the lists()method returns all the values from the given column. I can't even figure out why two different methods exist to do the same thing.

这让我很困惑。我看不出这两种方法有什么区别。如果我var_dump()是这些方法返回的对象,它们完全相同,但 Dayle Rees 的书说pluck()从给定列(第一个)返回单个值,而该lists()方法返回给定列中的所有值。我什至无法弄清楚为什么存在两种不同的方法来做同样的事情。

Example

例子

Route::get('getalbum', function() {
    $data = \App\Album::pluck('artist');
    var_dump($data); // a lot of text, let's call it 'object'

    $data = \App\Album::lists('artist');
    var_dump($data); // exact , exact, exact same 'object'
});

回答by Can Vural

From the docs, Deprecationssection

文档Deprecations部分

The following features are deprecated in 5.2 and will be removed in the 5.3 release in June 2016

The lists method on the Collection, query builder and Eloquent query builder objects has been renamed to pluck. The method signature remains the same.

以下功能在 5.2 中已弃用,并将在 2016 年 6 月的 5.3 版本中删除

集合、查询构建器和 Eloquent 查询构建器对象上的列表方法已重命名为 pluck。方法签名保持不变。

So yes they are same. It's just there for backward compatibility.

所以是的,他们是一样的。它只是为了向后兼容。

Source code

源代码