DB query builder toArray() laravel 4

前端 未结 7 1257
野性不改
野性不改 2021-02-01 13:32

I\'m trying to convert a query to an array with the method toArray() but it doesn\'t work for the query builder. Any ideas for convert it?

Example



        
相关标签:
7条回答
  • 2021-02-01 13:48

    toArray is a model method of Eloquent, so you need to a Eloquent model, try this:

     User::where('name', '=', 'Jhon')->get()->toArray();
    

    http://laravel.com/docs/eloquent#collections

    0 讨论(0)
  • 2021-02-01 13:48

    try this one

    DB::table('user')->where('name','Jhon')->get();
    

    just remove the "=" sign . . . .because you are trying to array just the name 'jhon' . . . . . . . .I hope it's help you . .

    0 讨论(0)
  • 2021-02-01 13:51

    And another solution

    $objectData = DB::table('user')
        ->select('column1', 'column2')
        ->where('name', '=', 'Jhon')
        ->get();
    $arrayData = array_map(function($item) {
        return (array)$item; 
    }, $objectData->toArray());
    

    It good in case when you need only several columns from entity.

    0 讨论(0)
  • 2021-02-01 14:03

    Please note, the option presented below is apparently no longer supported as of Laravel 5.4 (thanks @Alex).

    In Laravel 5.3 and below, there is a method to set the fetch mode for select queries.

    In this case, it might be more efficient to do:

    DB::connection()->setFetchMode(PDO::FETCH_ASSOC);
    $result = DB::table('user')->where('name',=,'Jhon')->get();
    

    That way, you won't waste time creating objects and then converting them back into arrays.

    0 讨论(0)
  • 2021-02-01 14:07

    You can do this using the query builder. Just use SELECT instead of TABLE and GET.

    DB::select('select * from user where name = ?',['Jhon']);
    

    Notes: 1. Multiple question marks are allowed. 2. The second parameter must be an array, even if there is only one parameter. 3. Laravel will automatically clean parameters, so you don't have to.

    Further info here: http://laravel.com/docs/5.0/database#running-queries

    Hmmmmmm, turns out that still returns a standard class for me when I don't use a where clause. I found this helped:

    foreach($results as $result)
    {
    print_r(get_object_vars($result));
    }
    

    However, get_object_vars isn't recursive, so don't use it on $results.

    0 讨论(0)
  • 2021-02-01 14:08

    If you prefer to use Query Builder instead of Eloquent here is the solutions

    $result = DB::table('user')->where('name',=,'Jhon')->get();
    

    First Solution

    $array = (array) $result;
    

    Second Solution

    $array = get_object_vars($result);
    

    Third Solution

    $array = json_decode(json_encode($result), true);
    

    hope it may help

    0 讨论(0)
提交回复
热议问题