Sanzeeb Aryal
Sanzeeb Aryal

Reputation: 3266

Accessing the table fields with relation yii2

Model users has onetomany relation with category

 public function getCategory() 
    {
         return $this->hasMany(Category::className(), ['user_id' => 'user_id']);
    }

I am not being able to access the fields of category using this relation.

   public function actionGetResults()
            {
                $results = users::find()->where(['user_id' =>8])
                                        ->with('category')
                                        ->all(); 

                echo "<pre>"; print_r($results);
            }

$results here shows an array with fields of category. i.e category_name, category_id etc. but if i do this:

 echo "<pre>"; print_r($results->category_name);

it fails.

Upvotes: 2

Views: 102

Answers (1)

arogachev
arogachev

Reputation: 33538

First of all, since relation type is has many, category name is misleading and it's better to use categories.

Second, you are accessing related field wrong. $results is an array of User models and categories property of each model contains an array of related Category models to that user.

Use nested foreach loop:

foreach ($results as $user) {
    foreach ($user->categories as $category) {
        var_dump($category->name);
    }
}

Or to get the name of the first user's first category:

$results[0]->categories[0]->name

Note that the second approach is only for demonstration purposes and can fail with Undefined index error if user or / and category does not exist.

Read Working with Relational Data for more info.

Upvotes: 3

Related Questions