Esaverelatedbehavior: Error When Saving

Hi, I have 3 table


Article

- id

- article


Tag

- id

- name

- slug


Tagged

- article_id

- tag_id

In my Article model, I have defined the following relation


'tags'=>array(

    self::MANY_MANY, 'Tag', 'tagged(article_id, tag_id)'

)

I then followed the extension’s guide and added the following into my Article’s create action:-


$article = new Article();

$article->tags = Tag::model()->findAll();

$article->saveWithRelated('tags');

I then got the following error


Table 'tags' does not have a column named "tagged(article_id, tag_id)"

Anyone got any idea what I have not done correctly? Do I have to specify a relation for my junction / join table?

Anyone can help me on this? thanks

Hi!

Read this thread, maybe you can get some useful information about your issue.

Hi Anonymous Joe,

I know it’s little bit late answer but I hope someone can gain from my experience.

I ran into same problem and find out where the bug is. The problem is not in yout model relation definition but in way (order) you are saving the models in your controller.


$article->saveWithRelated('tags');

Above method try to save main model with relateds together. This is allowed when you are upda-ting the main entry but not when you are creating new one. It’s because of this piece of code (ESaveRelatedBehavior.php line 215)




// Handle many_many relations, this check has to be done first, since CManyManyRelation extends CHasManyRelation

// The owner also needs to successfully saved, so that the foreign key can be determined

if ($relation instanceof CManyManyRelation && !$this->owner->isNewRecord)

{

...



So as the comment says "owner also needs to successfully saved" you must save owner model at first. You can do it like:




if($article->save()) 

{

  $article->saveRelated('tags');

}



So after owner model is succesfully saved you only need to save related models by using method "saveRelated".

Hope it will help someone.

I found out that ESaverelatedbehavir solve this but there is a little bug.

On line 200 in ESaveRelated.php you can add a simple IF condition




if ($result)

{

  foreach ((array) $relations as $key => $relationName)

  {

    ...



Because if owner would not be succesfully saved you cannot save related models.