MANY_MANY join table set up


I’ve been slowly learning to use Yii, and lately I am working my way through doing different types of object relationships. I felt I was doing alright with the One to Many relationships: but, now I am stuck on creating a simple Many to Many relationship between to objects, as I can’t find any info on setting up a 3rd join table that stores the id’s of the associated objects.

So far, I have two very simple models with CRUD actions: User and Document, which I am trying to set up in a many to many relationship. In the model files, my relation code looks like this:

Now after creating the tbl_user_document table, I can’t seem to find any information on setting the application up, so that when I create a new document, it will be related to the user(that created the document) through the join table.

Can anyone point me in the right direction, or give an outline of the steps involved in setting this up. Any help would be greatly appreciated!

I can’t figure out how I am supposed to insert the users id, and the documents id into the 3rd tbl_user_document join table. The relationship doesn’t seem to handle this automatically, which was the impression I get from the documentation.

Please help a Yii newbie. Yii has been really great so far: but, this has me stumped. :unsure:

Yii didn’t create the other two tables for you, so why are you expecting Yii to create the association table? You have to create it yourself.

I suggest you start by inserting some test data and try out a simple query. Then search the forum for more information on MANY_MANY, there are a number of extensions available that you may be interested in trying out.


I appreciate the reply Tommy, but as I stated above I created the 3rd join table and the relationships, but that is not the problem. I apologize if I wasn’t clear.

The problem I am having is after I have created the join table, and declared my relationships, I can’t figure out how to add a new record to the join table that actually makes the relationship work so I can call $user->documents to get a list of the users documents.

Since my last reply, I have come to believe that I need to add some code in the create action of my DocumentController, that adds a record to the join table when a new document is created. Again totally stuck though, and any help would be greatly appreciated with that.


So have you, as I suggested, manually added a small number of test records and tried out the relationship?

Have you searched the forum?

You’ll find useful extensions here.


Check out my reply to this thread.

Thanks to dniznick for the confirmation, and to the rest of you for trying to help a yii newb.

I finally got it working by creating a new instance of the join model in my create actions. I will post a brief overview of what I have done soon.