Astrotomic / laravel-translatable

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

how to select custom filed from translation table #264

Closed arbabi2010 closed 2 years ago

arbabi2010 commented 2 years ago

Hi , i want to select only title , slug from post_translations table and i won't select summary and other filed . how can i select specific column instead all fields .

github-actions[bot] commented 2 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

ast21 commented 1 year ago

@arbabi2010 hi! have you found a solution to your question?

Dezmonter commented 2 months ago

This is a big problem(We lose performance by selecting all translation fields(

Gummibeer commented 2 months ago

It's a full relational DB setup. In case you really care about that kind of performance you can go all in for a custom query - plain SQL or eloquent is up to you. But you are free to eagerly load the translations relationship or even the translation one with a callback and select only what you need. But that's up to you and your business logic. In case you find an easy to add but still flexible solution for a scope you can post it here and we can check if it's PR worthy or not.

Dezmonter commented 2 months ago

Here is my solution to this issue...

$doctorSpecialities = DoctorSpeciality::withTranslationOnly(['label', 'slug'])->get();


    public function scopeWithTranslationOnly(Builder $query, array $translationFields, ?string $locale = null)
    {
        $locale = $locale ?: $this->locale();

        array_push($translationFields, $this->getTranslationRelationKey(), 'language_id');

        $query->with([
            'translations' => function (Relation $query) use (;$translationFields, $locale) {
                if ($this->useFallback()) {
                    $countryFallbackLocale = $this->getFallbackLocale($locale); // e.g. de-DE => de
                    $locales = array_unique([$locale, $countryFallbackLocale, $this->getFallbackLocale()]);

                    return $query->whereIn($this->getTranslationsTable().'.'.$this->getLocaleKey(), $locales);
                }

                return $query->select($translationFields)->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), $locale);
            },
        ]);

```}
Gummibeer commented 2 months ago

416