Astrotomic / laravel-translatable

A Laravel package for multilingual models
https://docs.astrotomic.info/laravel-translatable/
MIT License
1.25k stars 157 forks source link

SELECT statement with translations #211

Closed ukropf closed 3 years ago

ukropf commented 3 years ago

How can I define translanable fields in Database SELECT statement? My code:

$posts = Post::select(
       [
             'id', 
            'translations.title', 
            'translations.body'
       ])
        ->with('translations')
        ->get();

Does not work.

ciamarro commented 3 years ago

You would probably need to do something like this (for english and french for example)

 $builder->selectRaw('en_translation.title as en_title, fr_translation.title as fr_title')
        ->leftJoin('post_translations AS en_translation', function ($j) {
            $j->on('post.id', '=', 'en_translation.post_id')
                ->where('en_translation.locale', '=', 'en');

        })
        ->leftJoin('post_translations AS fr_translation', function ($j) {
            $j->on('post.id', '=', 'en_translation.post_id')
                ->where('en_translation.locale', '=', 'fr');
github-actions[bot] commented 3 years ago

This issue is stale because it has been open 21 days with no activity. Remove stale label or comment or this will be closed in 7 days