Conditions for adding tags

I have modified the blog demo so a logged in user only sees their posts and related tags.

I have added an author_id column to the tags table so I can associate tags to a specific user. The following code in Tag.php allows a user to add new unique tags and it properly increments a user’s existing tags. Right now, it will not add a tag if that same tag was already added by another user. I want it to create duplicate tags if added by multiple members with each including their author_id. How can I get it to add a new tag if the tag name already exists but does not belong to the logged in user?

Thanks for your help!

public function addTags($tags)

{


	$criteria=new CDbCriteria;


	$criteria->condition='author_id='.Yii::app()->user->id;


	$criteria->addInCondition('name',$tags);


	$this->updateCounters(array('frequency'=>1),$criteria);


	foreach($tags as $name)


	{


		if(!$this->exists('name=:name',array(':name'=>$name)))


		{


			$tag=new Tag;


			$tag->name=$name;


			$tag->frequency=1;


			$tag->author_id=Yii::app()->user->id;


			$tag->save();


		}


	}


}

It should be possible, but why don’t you leave Tag as it is, and add a many-to-many table UserTag?

That way, if a user creates a new tag, you create it in the Tag table, otherwise you don’t. And, in both cases, you create the relationship in UserTag.

Thanks for your reply and suggestion. That probably would have been the best way from the beginning. But I was able to get it working by following some advice in this thread: http://www.yiiframework.com/forum/index.php/topic/13310-save-many-to-many-information/page__p__65282__hl__many-to-many+table#entry65282

Here is my working code with a defined default scope to search the tag table only for tags associated with the logged in user:

public function addTags($tags)

{


	//Check for existing tags for the logged in user and update counter


	$criteria=new CDbCriteria;


	$criteria->condition='author_id='.Yii::app()->user->id;


	$criteria->addInCondition('name',$tags);


	$this->updateCounters(array('frequency'=>1),$criteria);


	foreach($tags as $name)


	{


		$find = Tag::model()->find('name=:name',array(':name'=>$name));


		if(!$find)


		{


				$tag=new Tag;


				$tag->name=$name;


				$tag->frequency=1;


				$tag->author_id=Yii::app()->user->id;


				$tag->save();


		}


	}


}