DB query builder toArray() laravel 4

2019-03-11 16:19发布

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

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

7条回答
闹够了就滚
2楼-- · 2019-03-11 16:46

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.

查看更多
放荡不羁爱自由
3楼-- · 2019-03-11 16:54

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

查看更多
在下西门庆
4楼-- · 2019-03-11 16:54

And another solution

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

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

查看更多
可以哭但决不认输i
5楼-- · 2019-03-11 17:01

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

查看更多
够拽才男人
6楼-- · 2019-03-11 17:05

Easiest way is using laravel toArray function itself:

    $result = array_map(function ($value) {
        return $value instanceof Arrayable ? $value->toArray() : $value;
    }, $result);
查看更多
做自己的国王
7楼-- · 2019-03-11 17:08

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 . .

查看更多
登录 后发表回答