Laravel Fluent add select () s in separate places?

//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 add or enable a separate select function in the eloquent query constructor?

The actual -> select () is set earlier, and then this function is called. I would like to add a graph column conditionally in this later function to which the request was passed.

+6
source share
3 answers

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

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

+12
source

Yes, you just insert the block that you want to execute as a function .... according to the documentation Grouping parameters , you can do it like this ... passing the function Where a ...

This code below will probably not do what you want, but, there is something for you to build and play with.

 DB::table('users') ->where('name', '=', 'John') ->orWhere(function($query) { $query->group_by($value); ->select(DB::raw('COUNT('.$value.') as count')); }) ->get(); 
0
source

Try the following:

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

Also, if you are just trying to get an account and not picking a few things, you can use ->count() instead of ->get()

-1
source

Source: https://habr.com/ru/post/948014/


All Articles