2

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]
2
  • 2
    $result = array_column($result->toArray(), 'id'); perhaps? Commented May 11, 2015 at 18:31
  • json_decode($result,TRUE); Commented May 11, 2015 at 18:31

2 Answers 2

7

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')

Sign up to request clarification or add additional context in comments.

1 Comment

Using pluck is not good when you are dealing with bulk data. It is pretty slow.
6

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)

7 Comments

This returns null. However, using it to query other field works as expected. What? return DB::table('genres') ->join('albumGenres', 'genres.id', '=', 'albumGenres.genre_id') ->join('albums', 'albumGenres.album_id', '=', 'albums.id' ) ->select('genres.name') ->where('albumGenres.album_id','=',$this->id)->lists('name');
@Vector I just edited my answer, try again with updated code.
@Vector replace ->lists('genres.id'); with ->toSql(); and paste result here.
select 'genres'.'id' from 'genres' inner join 'albumGenres' on 'genres'.'id' = 'albumGenres'.'genre_id' inner join 'albums' on 'albumGenres'.'album_id' = 'albums'.'id' where 'albumGenres'.'album_id' = ? (Replaced back ticks with quotes)
@Vector please run this query in mysql/pgsql console (don't forget to replace ? with id you want) and paste result here.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.