views:

374

answers:

3

Hello, I have a question about Doctrine ORM M:M. I built some tables like this: -User +id +name -Group +id +name

I want to link these table via a new table with Doctrine: In Group class:

$this->hasMany('User as Users', array(
            // I'm wondering what I can fill here
            'refClass' => 'UserGroup'
        ));

and in the User class:

 $this->hasMany('Group as Groups', array(
                // I'm wondering what I can fill here
                'refClass' => 'UserGroup'
            ));

Please help me fill the blank. Thanks. Looking forward to hearing from you soon.

P/S:Sorry for my English

A: 

Group:

$this->hasMany('User as Users', array(
  'refClass' => 'UserGroup',
  'local' => 'group_id',
  'foreign' => 'user_id');

User:

$this->hasMany('Group as Groups', array(
  'refClass' => 'UserGroup',
  'local' => 'user_id',
  'foreign' => 'group_id');
DuoSRX
+1  A: 

There is some nice documentation for this at http://www.doctrine-project.org/documentation/manual/1_2/en/defining-models#relationships:join-table-associations:many-to-many servicing exactly your model.

Basically this code in the User table class:

$this->hasMany('Group as Groups', array(
                'local' => 'user_id',
                'foreign' => 'group_id',
                'refClass' => 'UserGroup'
            )
        );

states that the Group table is related, via the UserGroup intersection table. The "user_id" column in UserGroup is the key that matches the local table (User) and "group_id" is the key that matches in the foreign table (Group).

A similar statement in the Group table class provides the reverse:

$this->hasMany('User', array(
                'foreign' => 'user_id',
                'local' => 'group_id',
                'refClass' => 'UserGroup'
            )
        );
thank u guys so much
Ru Sh
A: 

Hi,

you could use ORM Designer for the M:N relationship definitions:

http://www.orm-designer.com/article/doctrine-many-to-many-relationship-in-orm-designer-1-3-x

There's a 14 day trial version during which you should be able to create your schema and you can learn how the YAML output should look like.

Frantisek Troster