Laravel 5.2 - pluck() 方法 returns 数组

Laravel 5.2 - pluck() method returns array

我正在尝试升级我的项目 L5.1 -> L5.2。在 upgrade guide 中,有一件事我不清楚:

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

没关系,将重构从 lists() 重命名为 pluck() 不是问题。但是 L5.0 和 L5.1 中有用的 pluck() 方法呢?

来自5.0 documentation

Retrieving A Single Column From A Row

$name = DB::table('users')->where('name', 'John')->pluck('name');

L5.2 中旧 pluck() 方法的替代方法是什么?

更新:

示例:

var_dump(DB::table('users')->where('id', 1)->pluck('id'));

L5.1:

// int(1)

L5.2:

// array(1) { [0]=> int(1) }

pluck() 的当前备选方案是 value()

在原始示例中,为什么不在数据库查询中使用 select() 方法?

$name = DB::table('users')->where('name', 'John')->select("id");

这将比使用 PHP 框架更快,因为它将利用 SQL 查询为您执行行 selection。对于普通集合,我认为这不适用,但由于您使用的是数据库...

幼虫 5.3:Specifying a Select Clause

laravel 提取 returns 一个数组

如果您的查询是:

 $name = DB::table('users')->where('name', 'John')->pluck('name');

那么数组是这样的(key是item的索引,自动递增的值):

[
    1 => "name1",
    2 => "name2",
    .
    .
    .
    100 => "name100"
]

但如果你这样做:

$name = DB::table('users')->where('name', 'John')->pluck('name','id');

那么key就是数据库中的实际索引。

key||value
[
    1 => "name1",
    2 => "name2",
    .
    .
    .
    100 => "name100"
]

您可以将任何值设置为键。

In Laravel 5.1+, you can use the value() instead of pluck.

要获得第一次出现,您可以使用

DB::table('users')->value('name');

或使用,

DB::table('users')->where('id', 1)->pluck('name')->first();

我使用 laravel 7.x 并且我用这个作为解决方法:->get()->pluck('id')->toArray();

它返回一个 ID 数组 [50,2,3],这是我使用的整个查询:

   $article_tags = DB::table('tags')
    ->join('taggables', function ($join) use ($id) {
        $join->on('tags.id', '=', 'taggables.tag_id');
        $join->where([
            ['taggable_id', '=', $id],
            ['taggable_type','=','article']
        ]);
    })->select('tags.id')->get()->pluck('id')->toArray();