Relations in model with primary key that is also foreign key

I was wondering if anyone can explain this to me, or go into the code in greater detail to see if it is unexpected behaviour:

I have, for example, three models (just to simplify),

model A

model B

model C

model A has primary key id,

model B has primary key A_id, which is also a foreign key referring to A.id (model B belong to A, and model A has one B)

model C has composite primary key (A_id, example_field1, example_field2), (where A_id is also a foreign key referring to A.id)

Now comes the slightly more complicated part - I want to create a relation in model B for model C, like the following:


        public function relations() {

		// NOTE: you may need to adjust the relation name and the related

		// class name for the relations automatically generated below.

		return array(

			'cs' => array(self::HAS_MANY, 'C', 'A_id', 'on' => 'b.example_field1 = \'btype\''),

		);

	}

Basically, I’m trying to say that B can have a variable number of Cs, when the Cs have the same A_id and their C.example_field1 equals a certain constant.

Now when I try to access B->Cs, I get an error attribute B->id does not exist. It would seem that the relation is looking to join C’s A_id to B’s id rather than B’s A_id, and this despite the fact that B’s primary key is properly defined as A_id (the problem is not due to field name collision either - I have tried naming C’s primary key as something else).

I have narrowed down the cause of this to around line 600 in the CActiveFinder class, where it seems that in getting the primary key for table B, it first checks table B’s list of foreign keys to see if there is one with the same name (which there obviously always will be, since A_id is both a primary and a foreign key), and uses the foreign key’s equivalent primary key (I assume that this refers to the relationship with model A, for which the key is obviously id) as primary key instead of the actual primary key.

I haven’t had time to delve any further into this to see if this is expected behaviour (perhaps necessary for other relation types), but it certainly seems to me that this is undesirable, and that having a foreign key as primary key should not cause such a problem.

For the moment, my only workaround has been to add a getId() method to model B, which returns the B->A_id attribute. This seems to work fine, but I do not like to fudge things.

Any ideas / explanations gratefully received…

i seem to have a similar problem on my thread:

http://www.yiiframework.com/forum/index.php?/topic/25229-help-in-relations/