Astrotomic / laravel-translatable

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

withTranslation's eager loading #304

Open ronrun opened 1 year ago

ronrun commented 1 year ago

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 commented 1 year ago

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

https://github.com/Astrotomic/laravel-translatable/blob/a030356edc6a97a834b9e603d0997f0eb684cfdb/src/Translatable/Traits/Scopes.php#L109-L124