查询生成器获取结果数组而不是 Laravel 中的对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30175026/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 11:31:54  来源:igfitidea点击:

Query builder get array of results instead of objects in Laravel

phplaravelquery-builder

提问by Vector

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]

回答by Limon Monte

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

只需使用->lists('id')而不是->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)

阅读更多:http: //laravel.com/docs/5.0/queries#selects(检索列值列表部分)

回答by Sebastien

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

在新版本的 Laravel 中,你应该使用 pluck() 而不是 list()。

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

这是文档中的参考:https: //laravel.com/docs/5.4/queries#retrieving-results(参见“检索列值列表”)