Imagine I have 3 tables:
School (PK: id_school)
Class (PK: id_Scholl, id_Class)
Student (PK: Id_Student; Fields: Id_school, Id_Class)
Then, at Class model, I defined the following relation:
'count_student' =>
array(self::STAT, 'student', 'id_school,id_class'),
It doesn’t work. Yii says that my foreign key is invalid (I’ve already checked my FKs)
Debugging I’ve reached at CActiveFinder > CStatElement > queryOneMany:
if(isset($table->foreignKeys[$fk]))
{
list($tableName,$pk)=$table->foreignKeys[$fk];
if($schema->compareTableNames($pkTable->rawName,$tableName))
$map[$pk]=$fk;
else{
throw new CDbException(Yii::t('yii','The relation "{relation}" in active record class "{class}" is specified with a foreign key "{key}" that does not point to the parent table "{table}".',
array('{class}'=>get_class($parent->model), '{relation}'=>$relation->name, '{key}'=>$fk, '{table}'=>$pkTable->name)));
}
}else{
if(is_array($table->primaryKey)) // composite PK
$map[$table->primaryKey[$i]]=$fk;
}
See the first line: if(isset($table->foreignKeys[$fk]))
For my Student AR, foreignKeys are defined as below:
[id_School] => table Class (Id_School) [?]
[id_Class] => table Class (Id_School, Id_Class)
When my relation checks for the id_Scholl field, it points to Class Table, not School table.
I’ve made a change so the previous code will check FIRST if the key is composed:
if(is_array($table->primaryKey)) // composite PK
$map[$table->primaryKey[$i]]=$fk;
elseif(isset($table->foreignKeys[$fk]))
{
list($tableName,$pk)=$table->foreignKeys[$fk];
if($schema->compareTableNames($pkTable->rawName,$tableName))
$map[$pk]=$fk;
else{
throw new CDbException(Yii::t('yii','The relation "{relation}" in active record class "{class}" is specified with a foreign key "{key}" that does not point to the parent table "{table}".',
array('{class}'=>get_class($parent->model), '{relation}'=>$relation->name, '{key}'=>$fk, '{table}'=>$pkTable->name)));
}
}
It works this way.