Simple 'many to many' question

Hi Guys,

Just starting with Yii, and have simple question.

I have Post and User models, you can vote up/down on Post.

When User votes, I’d like to insert (user_id,post_id) vote to the tbl_vote table.

Not sure what’s the best way of doing such a thing. I have all foreign keys setup, my relation entries look like this:

Post:


'tblUsers' => array(self::MANY_MANY, 'User', 'tbl_vote(post_id, user_id)')



User:


'tblPosts' => array(self::MANY_MANY, 'Post', 'tbl_vote(user_id, post_id)'),



In PostController I have this VoteUp action:


public function actionVoteUp($id)

	{

		$post = $this->loadModel($id);

		$post->score +=1;

		$post->save();

		echo "$post->score";

	}



How can I read if there is record in tbl_vote for this (user_id, post_id) and insert it if there is no such record ?

I know that I can do it by hardcoding sql query and runs it but shouldn’t I somehow use these tblUsers and tblPosts relations instead?

Your best bet is to create a model for your joining table. There are then a few ways that you could then check for the existence of the row using AR.

You’d probably still want to watch out for duplicate key errors from the database when inserting the new row because of the concurrency issues.

I just created Vote model, and added something like this:


		$vote=new Vote;

		$vote->user_id = Yii::app()->user->id;

		$vote->post_id = $id;

		$vote->save();

Looks like it’s working and is obvious :), but figured it out just few seconds after writing this post.

Thanks for help.

Cool. Make sure that you have a unique constraint (in the database) over the two columns to guarantee that each user can only vote once for each post.