Skip to content

Wrong query when using scopeWhereTranslation() with $locale parameter #436

@ashishov

Description

@ashishov

Describe the bug
Wrong query when using scopeWhereTranslation() with $locale parameter

To Reproduce
$application->whereTranslation('published_at', Carbon::now(), 'en', 'whereHas', '<=');

Expected behavior
current query is:
select * from applications where exists (select * from application_translations where applications.id = application_translations.application_id and application_translations.published_at <= ? and application_translations.locale <= ?);

expected query is:
select * from applications where exists (select * from application_translations where applications.id = application_translations.application_id and application_translations.published_at <= ? and application_translations.locale = ?);

The problem is
when $locale parameter passed it uses $operator parameter for building query for locale (application_translations.locale <= ?), should use '=' for locale operator in any case.

Versions (please complete the following information)

  • PHP: 8.3
  • Database: Mysql 8
  • Laravel: 10.48
  • Package: 11.15.1

Additional context
File: src/Translatable/Traits/Scopes.php
Line: 93
Method:

public function scopeWhereTranslation(Builder $query, string $translationField, $value, ?string $locale = null, string $method = 'whereHas', string $operator = '=')
    {
        return $query->$method('translations', function (Builder $query) use ($translationField, $value, $locale, $operator) {
            $query->where($this->getTranslationsTable().'.'.$translationField, $operator, $value);

            if ($locale) {
                $query->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), $operator, $locale); 
            }
        });
    }

I assume this method should look like this:

public function scopeWhereTranslation(Builder $query, string $translationField, $value, ?string $locale = null, string $method = 'whereHas', string $operator = '=')
    {
        return $query->$method('translations', function (Builder $query) use ($translationField, $value, $locale, $operator) {
            $query->where($this->getTranslationsTable().'.'.$translationField, $operator, $value);

            if ($locale) {
                $query->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), $locale); // removed $operator
            }
        });
    }

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions