laravel grouping by multiple columns - php

Im using laravel 5.2 and I want to group a table based on the value of two columns (configuration and type). So basically if two or more rows in the table have the same configuration and type they will be grouped.
I've tried querying like this and its not working:
$groups = Model::where('active', 1)->get()->groupBy('type_id', 'configuration_id');
Any suggestions?
EDIT: I think I'm using the wrong query. What I want to do is get the rows that have the same values in these two columns and have them grouped. Apparently group by is used to aggregate things e.g if I want a sum or something.
EDIT 2: Actually the groupby here I'm using is not part of the query it is a helper function provided by laravel to use on collections see this link Does anyone know if it groups by two feilds??

Ok I've figured it out.
The groupBy method I'm using is not a query it is a laravel function that groups collections by a certain field. You can see the documentation here. So the workaround was to do the grouping twice like this.
$groups = Model::where('active', 1)->get()->groupBy('type_id');
foreach ($groups as $group) {
$grouped[] = $group->groupBy('configuration_id');
}

Pass Columns names in array form this is working for me
$groups = Model::where('active', 1)->groupBy(['type_id', 'configuration_id','etc']);

$groups = Model::where('active', 1)->groupBy('type_id', 'configuration_id')->get();

Try like this
$groups = Model::where('active', 1)->groupBy('type_id', 'configuration_id');

$groups = Model::where('active', 1)->groupBy('type_id', 'configuration_id')->get(['type_id', 'configuration_id']);

Related

Laravel convert resultset to array

Database table SITE has many columns. One of them is site_id. I need all the site_ids as an array since it has to be fed to a method which accepts only a string array.
What I tried so far is:
$sites = DB::select('select site_id from site_tab');
$sites_arr = $sites->toArray();
But this doesn't produce the result I want. I need $sites_arr to be like ['A','B','C',...]
Please suggest a way to get this done. A solution based on Eloquent is also OK for me.
Thanks
Try this:
DB::table('site_tab')->pluck('site_id')->toArray();
reference pluck
referen toArray
If you open a manual, you will see that
The select method will always return an array of results
So, there's no need to use ->toArray(), as result is already an array.
To get values as array of names you can do:
$site_ids = DB::table('site_tab')->pluck('site_id');
Using ->toArray() here is optional, as you can iterate over $site_ids (which is a Collection) with a foreach too.

Laravel Eloquent return count of each group with groupBy()

I want to groupBy() task using Laravel Eloquent. I have searched Internet and didn't find anything with eloquent.
some people used groupBy() query with Query Builder like this link
But I want to create query like this style:
Task::select('id')->groupBy('category_id')->count();
This code just return only count of first category_id. But I want count of all the category_id.
Native Collection alternative (grouped by php, not mysql). It's a nice option when you have the Collection as variable already assigned. Of course is less optimal than mysql grouping in most cases.
$tasks->groupBy('category_id')->map->count();
You should add the count to the select function and use the get function to execute the query.
Task::select('id', \DB::raw("count(id)"))->groupBy('category_id')->get();
The \DB::raw() function makes sure the string is inserted in the query without Laravel modifying its value.
More simple:
Task::select('id')->groupBy('category_id')**->get()**->count();
You can do something like this:
return DB::table('offers')->select('*', DB::raw('count('.$field.') as total_count'))->groupBy($field)->get();
I overrode the count() method in my model. Could be something like:
public function count($string = '*'){
$tempmodel = new YourModel();
return $tempmodel ->where('id',$this->id)->where('category_id',$this->category_id)->count($string);
}
This gave me exactly the behavior of count() I was looking for.
Worked for me as
we need to select one column like 'category_id' or 'user_id' and then
count the selected column on get()
Task::select('category_id')
->where('user_id',Auth::user()->id)
->groupBy(['category_id'])
->get()
->count();
This works for me.
output:
return $email_trackers = EmailTracker::get()->groupBy('campaign_id')->map->count();
{
"6": 2
}

Using Array in '->where()' for Laravel Query Building

I am trying to get all values of a column, and then use it in another query. I used lists and got the values as an array but, I couldn't find the way to check that variable (array containing each id) in other query
$subscribes = Subscribe::where('from_id', $currentUser)->lists('id')
// dd($subscribes), logs values as array.
$videos = Photo::where('id', $subscribes)->get();
This doesn't work because $subscribes is an array.
Should I use a for loop and send another query for each id? Or is there a practical way that I am missing out? What is the proper way of using it?
Use whereIn method:
$videos = Photo::whereIn('id', $subscribes)->get();
http://laravel.com/docs/5.1/queries (scroll down / search 'whereIn')
Apply whereIn method
if(is_array($subscribes) && count($subscribes) > 0){
$videos = Photo::whereIn('id', $subscribes)->get();
}

Using aliases with eloquent

When I tried using alias using select with eloquent, it has given me weird results
my code:
$caseStudy = CaseStudy::find($id)->select('title_case as title','description_case as description')->get();
It returned collection. My question is to find model and change the column names. How to do it?
The find function can take an array as a second parameter.
In this array you can list the fields you need.
$caseStudy = CaseStudy::find($id, ['title_case as title','description_case as description']);
This way you should be able to access your aliases:
$caseStudy->title
Instead of:
$caseStudy->title_case
try using this
$caseStudy = CaseStudy::select(DB::raw('title_case as title','description_case as description'))->find($id)->get();

How do I write a search query using Kohana PHP?

I have a table (product_shoppingcart) with 4 columns :
id, product_id, shoppingcart_id, product_quantity.
I'm using Kohana's ORM.
I want to write a search query which returns all the rows where the shoppingcart_id column contains 1 (for example).
I already tried:
$arr = ORM::factory('product_shoppingcart')->where('shoppingcart_id',$shoppingcartID)->find_all();
but that doesn't work.
Can anyone please help me out?
Your example code should work, but perhaps the problem is that you're not iterating over your result set?
$results = ORM::factory('product_shoppingcart')
->where('shoppingcart_id', $shoppingcartID)
->find_all();
foreach ($results as $product_shoppingcart) {
print Kohana::debug($product_shoppingcart->as_array());
}
If you have more than one row with that id, this should give you a result iterator in $results, which you then walk with the foreach loop. I have lots of examples of similar working code, if you're still not able to get it working.
Here is what it would look like:
$arr = ORM::factory('product_shoppingcart')->where(
'shoppingcart_id',"=",$shoppingcartID)->find_all();
Shouldnt your table be "product_shoppingcarts" or am I missing something?

Categories