OmgDef / yii2-multilingual-behavior

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

multilingual dosen't work with asArray #19

Closed abdullah-almesbahi closed 9 years ago

abdullah-almesbahi commented 9 years ago

Hello , I was testing multilingual behavior. It's working great , but when I use asArray() , it doesn't work with it.

            $rows = static::find()
                ->orderBy('parent_id ASC, sort_order ASC')
                ->asArray()
                ->all();
        foreach($rows as $model){
            echo $model->name; 
        }

is there any work around for this issue ?

OmgDef commented 9 years ago

@cadr-sa Hi! In this case I'm always write some helper method like this

    public static function getAttribute($model, $attribute)
    {
        return isset($model['translation'][$attribute]) ? $model['translation'][$attribute] : $model[$attribute];
    }

      $rows = static::find()
                ->orderBy('parent_id ASC, sort_order ASC')
                ->asArray()
                ->all();
        foreach($rows as $model){
            echo SomeClass::getAttribute($model, 'name'); 
        }
abdullah-almesbahi commented 9 years ago

I have found this in your test directory and it is worked for me , but it's ugly hack. Any idea to improve this?

    public function testFindPosts()
    {
        $data = [];
        $models = Post::find()->multilingual()->all();
        foreach ($models as $model) {
            $this->assertEquals($model->title, $model->title_ru);
            $this->assertEquals($model->body, $model->body_ru);
            $this->assertNotNull($model->title_en);
            $this->assertNotNull($model->body_en);
            $data[] = $model->toArray([], ['translations']);
        }
        $this->assertEquals(require(__DIR__ . '/data/test-find-posts.php'), $data);
    }
abdullah-almesbahi commented 9 years ago

Thank you for your fast reply , I'm trying to find out a better way without using additional method to make it work

just with asArray()

OmgDef commented 9 years ago

@cadr-sa To implement this we should directly modify generated sql query

abdullah-almesbahi commented 9 years ago

why we shouldn't do it then?

OmgDef commented 9 years ago

@cadr-sa This will break backward compatibility

OmgDef commented 9 years ago

@cadr-sa https://github.com/vanik/yii2-multilingual-behavior/blob/master/MultilingualTrait.php

abdullah-almesbahi commented 9 years ago

Thank you for explanation.