-1

I am new to YII2 and I have a problem with my relationships:

I have Users and Category. They have a m-m relationship. Now i would like to see the Categories a user has. For that I made a table named "user_category" which looks as follows: enter image description here

In my models i have the following code as suggested in How do I work with many-to-many relations in Yii2 :

public function getUsers(){
    return $this->hasMany(TabUser::className(), ['intUserID' => 'intUserID'])
        ->viaTable('user_category', ['intCategoryID' => 'intCategoryID']);
}
public function getCategories(){
    return $this->hasMany(TabCategory::className(), ['intCategoryID' => 'intCategoryID'])
        ->viaTable('user_category', ['intUserID' => 'intUserID']);
}

Then i linked them together:

if($user->validate()) {
        $user->link('categories', $category);
    }

    var_dump($user->getCategories());

But this does not return my categories it returns the following: enter image description here

Does anybody know what I do wrong?

Thanks for your time and help!!

eibersji
  • 1,218
  • 4
  • 29
  • 52
  • Maybe this can help you [https://www.yiiframework.com/wiki/780/drills-search-by-a-hasmany-relation-in-yii-2-0](https://www.yiiframework.com/wiki/780/drills-search-by-a-hasmany-relation-in-yii-2-0) – Sfili_81 Oct 17 '18 at 06:49

2 Answers2

1

Try to divide your expression like this, should work:

$categories = $user->categories;
var_dump($categories);
Marat Badykov
  • 824
  • 4
  • 8
0

Method getCategories() returns ActiveQuery object instead of models. If you need to get an array of category models you must use magical property categories. For example:

var_dump($user->categories);
Maksym Fedorov
  • 6,383
  • 2
  • 11
  • 31
  • Thanks this has been helpful. I know it is not part of the question but you seem to have a clue. Do you know how to create a user with checkboxes for the categories? – Noé Perracini Oct 17 '18 at 07:04
  • You can use https://github.com/voskobovich/yii2-many-to-many-behavior to saving a category list – Maksym Fedorov Oct 17 '18 at 07:07