Astrotomic / laravel-translatable

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

N+1 query problem #252

Closed bitskina closed 2 years ago

bitskina commented 2 years ago

When I need to select non translatable fields for example only id and call Model::all(['id']) it still tries to load translations and runs N+1 query. image image

Gummibeer commented 2 years ago

Hey, first of all you can call with('translations') to prevent any n+1 query problem. Secondly You should use Model::query()->pluck('id') if you only need a single column. Next is that returning a model collection as response and using the models implicit array casting is bad practice. You should always use explicit resource classes for API/JSON responses: https://laravel.com/docs/8.x/eloquent-resources

And in case you need multiple columns which aren't translated and you haven't enabled loaded the translations it will not load them with explicit mapping as long as you don't use any translated attribute.

Your implicit array problem is likely an unwanted configuration on your end: https://github.com/Astrotomic/laravel-translatable/blob/ccf622f4400b8642865e755879c7f40980fb6138/src/config/translatable.php#L133

bitskina commented 2 years ago

Ok, thanks. It was just an example screens to describe a problem.