简体   繁体   中英

YII2 how do i handle many to many relationships?

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

I have Users and Category. They have a mm 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: 在此处输入图片说明

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: 在此处输入图片说明

Does anybody know what I do wrong?

Thanks for your time and help!!

Try to divide your expression like this, should work:

$categories = $user->categories;
var_dump($categories);

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM