dimsav / laravel-translatable

[Deprecated] A Laravel package for multilingual models
MIT License
1.95k stars 320 forks source link

How we can lazy load all translations to current model? #497

Closed Victorlerner closed 6 years ago

Victorlerner commented 6 years ago

Hi, How we can lazy load all translations to current model? now i had 2 queries http://prntscr.com/k7hjst it's is possible to have 1 sql queries? for example if I have 10 post now it have make 20 queries, i thinks it's is big speed issues. http://prntscr.com/k7hloh

Gummibeer commented 6 years ago

Just as every other eloquent relationship:

$modelWithTranslations = Model::with('translations')->get();
// or
$model = Model::all();
$model->load('translations');

And that's it! :)

Victorlerner commented 6 years ago

so I have this code now

    $categories =   $category->with('translations')->get()->groupBy( 'parent_id' );
        foreach ($categories as $category){
            dump($category->translations->title);
        }

but it get me this error Property [translations] does not exist on this collection instance. in Category.php I have this

    public function CategoryTranslation()
    {
        return $this->hasMany('Corp\CategoryTranslation');
    }

can you help with this?

Gummibeer commented 6 years ago

And is $category a QueryBuilder instance or an already loaded model or a model collection? Depending on this you have to use load('translations') if it's an EloquentCollection or Model instance. Just if it's an EloquentQueryBuilder you can use with().

Have you added the trait? You don't have to add this relation by your own - it is added by the trait: https://github.com/dimsav/laravel-translatable/blob/5a63ed1d0b872f6cd52d436262952eef0041d6ce/src/Translatable/Translatable.php#L138-L144