Astrotomic / laravel-translatable

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

How do I get only the "title" column, excluding the "content" column? #343

Closed ast21 closed 1 year ago

ast21 commented 1 year ago

Good afternoon!

I have a table of articles and article_translations. article_translations contains two translatable columns title and content. The content column can contain more than 10,000 characters. To get all the articles I do this:

Article::withTranslation()->paginate(50);

and this code get all translated columns, including content, but the content column is not needed, and loads the request

How do I get only the title column, excluding the content column?

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

hello, any updates and answers?

omarcinkonis commented 1 year ago

Hi, I found your question because I had a similar issue. To avoid loading unnecessary columns, you can add disableAutoloadTranslations() to the constructor of your model:

    public function __construct()
    {
        parent::__construct();

        self::disableAutoloadTranslations();
    }

If you want to disable autoload globally, you can change this translatable.php setting to false: 'to_array_always_loads_translations' => false,

Refer to: https://docs.astrotomic.info/laravel-translatable/package/methods#translation-autoloading

ast21 commented 1 year ago

Hi @omarcinkonis .

Thanks for your reply. Now I use that code:

Article::query()
    ->with('translations', function ($query) {
        $query
            ->select(['article_id', 'locale', 'title']) // without 'content' because it's too big
            ->where('locale', app()->getLocale());
    })
    ->paginate();

After that, I wrap it in ArticleResource, there I already bring it to the form I need.