I'm having trouble saving a many to many relation. My database schema are as below:-
articles
- id (PK)
- content
tags
- id (PK)
- name
article_tag
- article_id (PK)
- tag_id (PK)
My Article model has the following relation:-
'tags' => array(self::MANY_MANY, 'Tag', 'article_tag(tag_id, article_id)'),
However, when I saw using a Yii behavior, I get the following error:-
Table "tags" does not have a column named "article_tag(tag_id, article_id)".
I have run through everything from schema to relation and I can't seem to figure out the problem. I have tried using other extensions as well and none of them seem to save to the m:n table.
Am I missing something here?
Additional Information
Here is my CManyManyRelation Object; the foreignKey just doesn't look right.
CManyManyRelation Object ( [limit] => -1 [offset] => -1 [index] => [through] => [joinType] => LEFT OUTER JOIN [on] => [alias] => [with] => Array ( ) [together] => [scopes] => [name] => tags [className] => Tag [foreignKey] => restaurant_tag(restaurant_id, tag_id) [select] => * [condition] => [params] => Array ( ) [group] => [join] => [having] => [order] => [_e:CComponent:private] => [_m:CComponent:private] => )
In the Many-Many relation in the Article
class you should put first the id of the Article and then the id of the tag:
'tags' => array(self::MANY_MANY, 'Tag', 'article_tag(article_id, tag_id)'),
Then in the class Tag
you should have:
'articles' => array(self::MANY_MANY, 'Article', 'article_tag(tag_id, article_id)'),
Edit: My bad I didn't realize it was saving the related model that causes the problem. There is no build-in possibility to save the related record in Yii
For me the best solution to save a related models is the extension activerecord-relation-behavior. The extension will be handling all the HAS_MANY and MANY_MANY relations.