Laravel Fluent在不同的地方添加select()?

Dam*_*mon 10 mysql select fluent laravel eloquent

//Earlier in the code, in each Model:
query = ModelName::select('table_name.*')

//Later in the code in a function in a Trait class that is always called

    if ($column == 'group_by')
    {
        $thing_query->groupBy($value);
        $thing_query->select(DB::raw('COUNT('.$value.') as count'));
    }
Run Code Online (Sandbox Code Playgroud)

有没有办法在eloquent查询生成器中追加或包含单独的select函数?

实际的 - > select()先前设置,然后调用此函数.我想在后面的函数中有条件地添加count列,该函数将查询传递给它.

Cam*_*ron 14

为了将来参考,您可以使用addSelect()函数.

在文档中有好处,但您可以在API中找到它:http://laravel.com/api/4.2/Illuminate/Database/Query/Builder.html#method_addSelect


小智 -1

尝试这个:

$thing_query->groupBy($value)->get(DB::raw('COUNT('.$value.') as count'));

另外,如果您只是想获取计数而不选择多个内容,您可以->count()使用->get()