Problems With Many_Many Relations

Hi

I’ve run into a little problem regarding Many_Many relation.

3 tables




+----------------+	+----------------+	+----------------+

|     Address  	 |	| AddressRel	 |	|     Company    |

+----------------+	+----------------+      +----------------+

| Id  (PK)   	 |---+	| Id (PK)	 |   +--| CompanyId (PK) |

| CompanyId (PK) |   |  | CompanyId (PK) |   |	| ...		 |

| Primary	 |   +--| AddressId	 |   |	+----------------+

+----------------+	| RefTableName	 |   |

			| RefId		 |---+

			+----------------+



I’m trying to get the Primary address for a given company.

So I started by defining the address relation in Company model:




'addresses'=> array(self::MANY_MANY,'Address', 'AddressRelations(AddressId, RefId)', 

		    'condition' => 'RefTableName = :tableName',

                    'params' => array(':tableName' => $this->tableName()),

                    'together' => false),



Address table has the following default scope (cmpId = CompanyId):




return array('condition' => $this->getTableAlias(false, false) . ".CompanyId=" . Yii::app()->user->getState('cmpId'));



And the named scope:




'primary' => array('condition' => 'Primary=1')



The idea was to access the default address by




Company::model()->addresses(array('scopes' => array('primary')))->find();



The address table can hold addresses for other tables then Company, thats why the AddressRelation table has the fields RefTableName and RefId.

I’m not sure I’ve set up the relation correctly and are a bit lost of where to look.

Could anyone help me defining this relation?