Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

withTranslation's eager loading #304

Open
ronrun opened this issue Oct 21, 2022 · 1 comment
Open

withTranslation's eager loading #304

ronrun opened this issue Oct 21, 2022 · 1 comment

Comments

@ronrun
Copy link

ronrun commented Oct 21, 2022

Describe the bug
According to the docs, this is eager loading.
Post::withTranslation()->get();
It actually is. But when do the foreach

            foreach ($rows as $key => $row) {            
                echo '<pre>', print_r($row->translation->name, 1), "</pre>";
            }

It does the sql query for every row. If 10 rows, it's 1 sql for my product table, 10 sql for product_relations table

But if I use laravel's default's with()
Product::with('translation')->get();
It's really eager loading.

So, maybe there is something wrong with the function withTranslation() ?

To Reproduce

        //$products = (new Product)->with('translation')->get();
        $products = (new Product)->withTranslation()->get();
        // echo '<pre>', print_r($products, 1), "</pre>"; // This is always eager loading.
        foreach ($products as $key => $row) {
            echo '<pre>', print_r($row->translation->name, 1), "</pre>"; // This depends.
        }
@Gummibeer
Copy link
Member

It doesn't load the translation relationship but filtered translations.

public function scopeWithTranslation(Builder $query)
{
$query->with([
'translations' => function (Relation $query) {
if ($this->useFallback()) {
$locale = $this->locale();
$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->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), $this->locale());
},
]);
}

# for free to join this conversation on GitHub. Already have an account? # to comment
Development

No branches or pull requests

2 participants