Laravel: getting a a single value from a MySQL query

前端 未结 6 1782
[愿得一人]
[愿得一人] 2021-02-03 17:27

I\'m trying get a single value from MySQL database using laravel but the problem I\'m getting an array . this is my query result in MySQL command line:

select gr         


        
6条回答
  •  失恋的感觉
    2021-02-03 17:59

    yet another edit: As of version 5.2 pluck is not deprecated anymore, it just got new behaviour (same as lists previously - see side-note below):

    edit: As of version 5.1 pluck is deprecated, so start using value instead:

    DB::table('users')->where('username', $username)->value('groupName');    
    

    // valid for L4 / L5.0 only
    DB::table('users')->where('username', $username)->pluck('groupName');
    

    this will return single value of groupName field of the first row found.


    SIDE NOTE reg. @TomasButeler comment: As Laravel doesn't follow sensible versioning, there are sometimes cases like this. At the time of writing this answer we had pluck method to get SINGLE value from the query (Laravel 4.* & 5.0).

    Then, with L5.1 pluck got deprecated and, instead, we got value method to replace it.

    But to make it funny, pluck in fact was never gone. Instead it just got completely new behaviour and... deprecated lists method.. (L5.2) - that was caused by the inconsistency between Query Builder and Collection methods (in 5.1 pluck worked differently on the collection and query, that's the reason).

提交回复
热议问题