0

I have following structure, just attaching screenshot for reference, consider the attached image is my sql schema

enter image description here

This is what I am trying to get

$array = [
    [
        'city'  =>  1,
        'google'=>  [4,2]
    ],
    [
        'city'  =>  2,
        'google'=>  [3,2,1]
    ],
];

I have used Postgresql

I tried with group by though no logic behind my implementation, no magic involved in laravel

$models = Model::groupBy('city')->get();

Can anyone help to find the way?

Thought of doing it through loop but would like to know the efficient way of doing it.

2
  • city one should have 4 and 3 as per file,,right? Commented Aug 10, 2016 at 7:41
  • @DanyalSandeelo yes you are right Commented Aug 10, 2016 at 7:44

2 Answers 2

2
$models = Model::groupBy('city')->selectRaw('city, GROUP_CONCAT(google) as google')->get();

Try this out. This would group concat the result for mysql.

 $models = Model::groupBy('city')->selectRaw('city, array_agg(google) as google')->get();

as per here, there is an alternate for group_concat in Postgres.

Sign up to request clarification or add additional context in comments.

3 Comments

It is postgresql and not mysql
stackoverflow.com/questions/2560946/… THis contains the equivalent method for group_concat.
Yes it works, but it is in different format of array like it returns {4,2} instead of [4,2]
1

You can query directly like this

$resultSet =  DB::select(DB::raw(" SQL QUERY HERE"));

and in models you can do it like

$resultSet = DB::table('table_name')
            ->groupBy('column_name')
            ->get();

While in your case you won't need group, you will need group_concat. Have a look here http://www.w3resource.com/mysql/aggregate-functions-and-grouping/aggregate-functions-and-grouping-group_concat.php

Here is what I did:

enter image description here

For postgreSQL use this syntax

   SELECT city, 
   string_agg(google, ',')
   FROM test
   GROUP BY city

5 Comments

but I don't think this will give me the expected output
actually it is Postgresql
string_agg is not a postgresql function it throws exception
@overflow have a look here.. stackoverflow.com/questions/2560946/…
@overflow upvote or mark it as answered if it answered your question..mention postgresql in your question too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.