Laravel 5.2 - pluck() method returns array

前端 未结 5 734
悲&欢浪女
悲&欢浪女 2020-12-04 21:13

I\'m trying to upgrade my project L5.1 -> L5.2. In upgrade guide there\'s one thing which isn\'t clear for me:

The lists method on the Co

相关标签:
5条回答
  • 2020-12-04 21:49

    In the original example, why not use the select() method in your database query?

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

    This will be faster than using a PHP framework, for it'll utilize the SQL query to do the row selection for you. For ordinary collections, I don't believe this applies, but since you're using a database...

    Larvel 5.3: Specifying a Select Clause

    0 讨论(0)
  • 2020-12-04 22:04

    The current alternative for pluck() is value().

    0 讨论(0)
  • 2020-12-04 22:10

    laravel pluck returns an array

    if your query is:

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

    then the array is like this (key is the index of the item. auto incremented value):

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

    but if you do like this:

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

    then the key is actual index in the database.

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

    you can set any value as key.

    0 讨论(0)
  • 2020-12-04 22:12

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

    To get first occurence, You can either use

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

    or use,

    DB::table('users')->where('id', 1)->pluck('name')->first();
    
    0 讨论(0)
  • 2020-12-04 22:12

    I use laravel 7.x and I used this as a workaround:->get()->pluck('id')->toArray();

    it gives back an array of ids [50,2,3] and this is the whole query I used:

       $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();
    
    0 讨论(0)
提交回复
热议问题