OmgDef / yii2-multilingual-behavior

Yii2 port of the yii-multilingual-behavior.
146 stars 60 forks source link

Problem with SearchModel when using related model translation sorting (if related model can be null) #86

Open Matvik opened 4 years ago

Matvik commented 4 years ago

Hello! Suppose we have a shop and a shop category. Both are multilingual. If we need to have sorting by the category field in gridview, it should be described like this:

   $query = Shop::find()->alias('s')->joinWith(['translation t', 'category.translation ct']);
   $dataProvider = new ActiveDataProvider([
       'query' => $query,
   ]);
   $dataProvider->setSort([
       'attributes' => [
          'id',
          'name' => [
               'asc' => ['t.name' => SORT_ASC],
               'desc' => ['t.name' => SORT_DESC],
          ],
          'category_id' => [
               'asc' => ['ct.name' => SORT_ASC],
               'desc' => ['ct.name' => SORT_DESC],
         ],
         'defaultOrder' => [
             'id' => SORT_DESC,
        ],
  ]);

All works fine, if shop always has category. But when a non-category shop is allowed (category_id can be null) we have a problem: there is no category translations without category so additional condition from translation relation returns false (WHERE (cat_language='uk')) and shops without category are not displayd in the result. What we can do with this? Thanks

Matvik commented 4 years ago

Any updates?

Matvik commented 4 years ago

Resolved by adding alternative relation to the behavior:

    public function getTranslationNullAllowed($language = null)
    {
        $ownerPrimaryKey = get_class($this->owner)::primaryKey()[0];
        $language = $language ?: $this->getCurrentLanguage();
        return $this->owner->hasOne($this->langClassName, [$this->langForeignKey => $ownerPrimaryKey])
            ->where(['or', 
                [$this->languageField => $language],
                [$this->languageField => null]
            ]);
    }

and using ->joinWith(['translation t', 'category.translationNullAllowed ct']) instead.

I can send pull request, if you want.