nik nik - 5 months ago 21
MySQL Question

How to convert rows into columns in laravel

I am totally new in web developing... What I want is this:

row records converted into columns in Excel

The records that i get have three main columns, 'DateTime', 'meter_type', 'value'... Now in here, meter_type have same values i.e. like from 1 to 8 (in image, it is 72 to 79) for different values of DateTime and value... As an example, at DateTime:

2016-06-23 00:01:00
, i get
8
different values for all
8
different meter types and similarly at DateTime:
2016-06-23 00:02:00
, i will get new set of 8 values for all meter_types...

Now what I want is, to group 'DateTime' column for different 'meter_type' i.e., in this case (above example), I want 9 columns (in total), 1 column for DateTime and remaining all 8 columns depicting 8 meter_type and records for these columns will be
value
of them... Please refer image for more clarification...

And I want to do this in travel using query builders or eloquent... I googled this, but I didn't found anything useful in travel for what I want... Please help me out here... documentations or properly detailed examples for achieving what I want will really be appreciated.

Answer

Look like a perfect use for the group by method on collections:

https://laravel.com/docs/master/collections#method-groupby

That way if you do

$collection->groupBy('meter_type');

You'll have an array using the meter type as key and all records regarding that meter type in each.