简体   繁体   中英

Laravel Eloquent GroupBy KeyBy

I have a languages table which has the following columns.

  • country_code
  • code
  • value

This table contains various codes which relate to different sections of my app. For example, the home screen might say welcome so the code for that phrase is "welcome". I would in the table store 3 variations in different languages and the country code would be set.

Example dataset

country_code  |  code     |  value
------------------------------------------------
EN            |  welcome  |  Welcome
FR            |  welcome  |  Bienvenue
DE            |  welcome  |  herzlich willkommen

I am trying to run a eloquent query which would return a result like the following: The idea is to have the results grouped by country_code then the keys of each result set as the code column.

{
  "EN": [
      "welcome": {
        "country_code": "EN",
        "value": "Welcome",
        "code": "welcome"
      },
      "goodbye": {
        "country_code": "EN",
        "value": "Goodbye",
        "code": "goodbye"
      }
  ],
  "FR": [
      "welcome": {
        "country_code": "FR",
        "value": "Bienvenue",
        "code": "welcome"
      },
      "goodbye": {
        "country_code": "FR",
        "value": "Au revoir",
        "code": "goodbye"
      }
  ],
  "DE": [
      "welcome": {
        "country_code": "DE",
        "value": "Herzlich Willkommen",
        "code": "welcome"
      },
      "goodbye": {
        "country_code": "DE",
        "value": "Auf Wiedersehen",
        "code": "goodbye"
      }
  ]
}

I've tried the following eloquent query but this doesn't return the above it does group by country code but then the results in the group don't have the key set for each value as the code column.

$languages = \App\Language::all();
return $language->keyBy('code')->groupBy('country_code');

You can use this:

Language::all()->groupBy('country_code')->map->keyBy('code');

This should give you your desired result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM