load as relations and return them using the $with property of the model
Dec 27, 2020
2
Level 14
How to return results from 3 different tables?
Hi, I am making a translation feature for my app. I have 3 tables - languages, language_translations and language_strings and I would like to return all the languages and their translations json as a result like this but not sure how to do it...
languages: [
en: {
lang_long: 'english',
translations: {
'good morning': 'good morning',
'welcome': 'welcome',
'bye': 'bye',
}
},
es: {
lang_long: 'español',
translations: {
'good morning': 'buenos días',
'welcome': 'bienvenidas',
'bye': 'adiós',
}
},
ru: {
lang_long: 'español',
translations: {
'good morning': 'доброе утро',
'welcome': 'добро пожаловать',
'bye': 'до свидания',
}
},
]
Here are my 3 tables
languages
+----+------------+-----------+
| id | lang_short | lang_long |
+----+------------+-----------+
| 1 | en | english |
| 2 | es | español |
| 3 | ru | русский |
+----+------------+-----------+
language_strings
+----+--------------+
| id | lang_string |
+----+--------------+
| 1 | good morning |
| 2 | welcome |
| 3 | bye |
+----+--------------+
language_translations
+----+----------------+---------+------------------+
| id | lang_string_id | lang_id | lang_translation |
+----+----------------+---------+------------------+
| 1 | 1 | 1 | good morning |
| 2 | 1 | 2 | buenos días |
| 3 | 3 | 3 | до свидания |
+----+----------------+---------+------------------+
I was thinking about looping over them and constructing it like this but I'm not sure how or even if this is the best way to do this.. (for performance)
$languages = Language::all();
$language_strings = LanguageString::all();
$language_translations = LanguageTranslation::all();
$languages->each(function($language, $key) use ($language_strings, $language_translations) {
// ...
});
Please or to participate in this conversation.