Skip to content

New scope to join translations #439

Open
@Oleksandr-Moik

Description

@Oleksandr-Moik

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');

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions