Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

New scope to join translations #439

Open
Oleksandr-Moik opened this issue Dec 17, 2024 · 0 comments
Open

New scope to join translations #439

Oleksandr-Moik opened this issue Dec 17, 2024 · 0 comments

Comments

@Oleksandr-Moik
Copy link
Contributor

I have the following scopes in one of my projects and I think it will be useful for others besides the current ones scopes.

Maybe I or others will add this to the package in the future, but for now just leave it here

public function scopeWithTranslations(Builder $query): Builder
{
    return $query->with([
        'translations' => function ($query) {
            $query->where('locale', app()->getLocale());
        },
    ]);
}

public function scopeJoinTranslations(
    Builder $query,
    ?string $modelTable = null,
    ?string $translationsTable = null,
    ?string $modelTableKey = null,
    ?string $translationsTableKey = null
): Builder {
    if (!$modelTable) {
        $modelTable = $this->getTable();
    }

    $singularModelTable = Str::singular($modelTable);

    if (!$translationsTable) {
        $translationsTable = $singularModelTable . "_translations";
    }

    $translationsTableKey = (empty($translationsTableKey) ? $singularModelTable . "_id" : $translationsTableKey);
    $modelTableKey = (empty($modelTableKey) ? "id" : $modelTableKey);

    return $query->leftJoin(
        $translationsTable,
        function ($join) use ($modelTable, $translationsTable, $translationsTableKey, $modelTableKey) {
            $join->on("{$translationsTable}.{$translationsTableKey}", '=', "{$modelTable}.{$modelTableKey}")
                ->where('locale', '=', app()->getLocale());
        }
    );
}

How it can be used? For example to create list for select field:

$options = Category::joinTranslations()->pluck('name', 'id');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

1 participant