简体   繁体   中英

Laravel 5.6 get all rows as arrays of values using Eloquent ORM

I have an eloquent query that returns a collection:

$items = Item::get(['id', 'name']);

When I convert to JSON I get this:

[
    {id: 1, name: "some name"},
    {id: 2, name: "some other name"}
]

I want a result like this instead:

[
    [1, "some name"],
    [2, "some other name"]
]

How can I achieve this with Laravel 5.6 and eloquent ORM?

You can use the toArray method

$items = Item::get(['id', 'name'])->map(function($item) {
    return array_values($item->toArray());
});

Your $item variable will have something like this :

Illuminate\Support\Collection {
     all: [
       [
        1,
        "Peter",
       ],
       [
         2,
         "Juan",
       ],
   ];

And the json representation :

[[1, "Peter"], [2, "Juan"]]

使用pluck方法来实现这一点

$items = \App\Item::pluck('name', 'id');

I was getting error about inner toArray() , so this worked for me:

$items = Item::get(['id', 'name'])->map(function($item) {
    return array_values((array)$item);
})->toArray();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM