Query builder get array of results instead of objects in Laravel

一个人想着一个人 提交于 2021-02-05 07:10:46

问题


Here's my query

DB::table('genres')
        ->join('albumGenres', 'genres.id', '=', 'albumGenres.genre_id')
        ->join('albums', 'albumGenres.album_id', '=', 'albums.id' )
        ->select('genres.id')
        ->where('albumGenres.album_id','=',$this->id)->get();

But I get something like this

"genre_id": [
        {
            "id": "4"
        },
        {
            "id": "8"
        }
    ]

What should I do to get the results as just an array

"genre_id" : [4,8]

回答1:


With new versions of Laravel, you should use pluck() instead of lists().

DB::table('genres')
->join('albumGenres', 'genres.id', '=', 'albumGenres.genre_id')
->join('albums', 'albumGenres.album_id', '=', 'albums.id' )
->where('albumGenres.album_id', '=', $this->id)
->pluck('genres.id');

Here is the reference in the documentation: https://laravel.com/docs/5.4/queries#retrieving-results (see 'Retrieving A List Of Column Values')




回答2:


Just use ->lists('id') instead of ->get():

DB::table('genres')
    ->join('albumGenres', 'genres.id', '=', 'albumGenres.genre_id')
    ->join('albums', 'albumGenres.album_id', '=', 'albums.id' )
    ->where('albumGenres.album_id', '=', $this->id)
    ->lists('genres.id');

Read more: http://laravel.com/docs/5.0/queries#selects (Retrieving A List Of Column Values section)



来源:https://stackoverflow.com/questions/30175026/query-builder-get-array-of-results-instead-of-objects-in-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!