I am using Laravel 5.1.
I have two database tables for multilingual data namely templates and translations as below:
templates:
id(PK) type template_text
1 reg abcd
2 otp def
and
translations:
id(PK) template_id(fk) locale_code translation
1 1 es xyzw
2 1 gu deft
3 2 es yrc
The basic idea is, templates table will have records in English language, and translations table will contain respective multilingual data.
For example, for templates table record with id=1 refers to two languages es and gu in translations table. And record with id=2 of templates table have only es language available in translations table.
Now, I want to fetch the respective language record from translations table for the provided template table's type, if not available then it will get the template table's record.
e.g., for type='reg', if I provide language='gu' then it should return "deft", but for type='otp', if I provide language='gu' then it should return "def" because in translations table there is no record for language="gu" is available.
I can achieve it using:
$template = Template::with(array('translations' => function($query){
return $query->where('language','=', 'gu');
}))->where('type', '=', 'reg')->first();
And I can get the translations as an empty array and can handle this using if empty translations then use template_text.
But I want to handle it smartly, something like using scope etc.
I have created scope in Translations model and tried using
$template = Template::with('translations')
->whereHas('translations', function($q){
$q->locale('gu');
})->where('type', '=', 'reg')->first();
But it seems little clumsy and unclear and giving error.
Is there any smart way to handle this?
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire