问题
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