Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to fetch from db with laravel using CONCAT and COUNT

In database I have table Users like this:

// id // name  // street  // house
--------------------------
// 1 // name1  // street1 // 1
// 2 // name2  // street1 // 1
// 3 // name3  // street1 // 1
// 4 // name4  // street2 // 2
// 5 // name5  // street3 // 3
// 6 // name6  // street4 // 4
// 7 // name7  // street5 // 5

I need to make a selection where I will get the full address and the number of records with that address in descending order for Users in users_ids array. The result should look like this:

 address     number
'street1 1'   3
'street2 2'   1
'street3 3'   1
'street4 4'   1
'street5 5'   1

in laravel i use query:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

        $recordsByAddresses = DB::table('users')
            ->whereIn('id', $users_ids)
            ->select(DB::raw("CONCAT(street, ' ', house) AS address"), DB::raw("COUNT(CONCAT(street, ' ', house)) AS number"))
            ->orderBy('number', 'desc')
            ->get();

As a result I get only one first address and the number of all addresses:

 address     number
'street1 1'   7

>Solution :

It’s untested but this might work:

$recordsByAddresses = DB::table('users')
    ->whereIn('id', $userIds)
    ->select(
        DB::raw('CONCAT(street, " ", house) AS address'),
        DB::raw('count(*) as total')
    )
    ->groupBy('address')
    ->orderBy('total', 'desc')
    ->get();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading