MANY to MANY relations ... how to define "both ways"?

Hi,

in the docs there is an example


class Post extends CActiveRecord

{

    public function relations()

    {

        return array(

            'categories'=>array(self::MANY_MANY, 'Category', 'PostCategory(postID, categoryID)'),

        );

    }

}



now let’s say I want to list posts belonging to given category. Thus I defined the Category model as following:


class Category extends CActiveRecord

{

    public function relations()

    {

        return array(

            'posts'=>array(self::MANY_MANY, 'Post', 'PostCategory(postID, categoryID)'),

        );

    }

}



unfortunately,

$cat->posts returns empty array, while $post->categories returns proper array of categories … What did I wrong?

Switch the keys around:




class Category extends CActiveRecord

{

    public function relations()

    {

        return array(

            'posts'=>array(self::MANY_MANY, 'Post', 'PostCategory(categoryID, postID)'),

        );

    }

}



That should do the trick.

Thanks, indeed it solved the problem.

Why there is a difference between


PostCategory(categoryID, postID)

and


PostCategory(postID, categoryID)

?

What about tables which have 3 or more primary keys ?


ABC (aID, bID, CiD)

The first argument is used to match to the primary key of the current model’s underlying table, the second one will be matched on the primary key of the related table.

I see, thx Sander.

You are quite experienced Yii developer Sander, aren’t U?

Heh, not really actually, I’ve only been using Yii for about two months now. However I am using it to build quite a complex app for the company I work for, so I’ve learned a lot since then! I actually ran into a kind of similar situation myself before, see [topic=5753]this thread[/topic] and [topic=5773]this thread[/topic], so I was a little familiar with the question…

Thanks for the compliment though :)