11
//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'));
    }

Is there a way to append or include a separate select function in the eloquent query builder?

The actual ->select() is set earlier and then this function is called. I'd like to add the count column conditionally in this later function that has the query passed into it.

Damon
  • 10,493
  • 16
  • 86
  • 144

3 Answers3

16

For future reference, you can use the addSelect() function.

It would be good to have in the documentation, but you'll find it here in the API: http://laravel.com/api/4.2/Illuminate/Database/Query/Builder.html#method_addSelect

Cameron
  • 995
  • 10
  • 16
  • That link doesn't work for me, this one does: http://laravel.com/api/4.2/Illuminate/Database/Query/Builder.html#method_addSelect – Benubird Jan 28 '15 at 16:05
0

Yeah you just insert the block you wanna execute as a function....according to the documentation on Parameter Grouping , you can do like so...by passing the Where a function...

This code below probably wont do what you want, but, its something for you to build off of, and play around with.

DB::table('users')
        ->where('name', '=', 'John')
        ->orWhere(function($query)
        {
            $query->group_by($value);
                  ->select(DB::raw('COUNT('.$value.') as count'));
        })
        ->get();
Kylie
  • 11,421
  • 11
  • 47
  • 78
-1

Try this:

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

Also,if you are just trying to get the count and not select multiple things you can use ->count() instead of ->get()

Community
  • 1
  • 1
coffe4u
  • 538
  • 3
  • 5