Hello,
is it possible to model ternary relationship with CActiveRecord?
I mean three tables and a relationship table with foreign keys into them.
Regards,
Jiri
Hello,
is it possible to model ternary relationship with CActiveRecord?
I mean three tables and a relationship table with foreign keys into them.
Regards,
Jiri
Hi jiri, welcome to the forum.
Would you please elaborate the issue and your needs with a sample?
For example,
Table_A ... id, name, field_a1, field_a2
Table_B ... id, name, field_b1, field_b2
Table_C ... id, name, field_c1, field_c2
Table_R ... a_id, b_id, c_id
...
The above is what comes to my mind with your brief explanation, but I couldn’t imagine any further about the relations between A, B and C.
Hi,
yes this is the schema I had in mind.
Now, say, the tables are department, section and budget. Meaning the department has separate budget for several sections.
Can I the get section/budget pars for the department via some CActiveRecord magic?
Of course I know how to do it in plain sql.
Thanks,
Jiri
I see.
As you see in the guide, Yii supports 4 kinds of relationship between the active record models.
http://www.yiiframework.com/doc/guide/1.1/en/database.arr#declaring-relationship
BELONGS_TO, HAS_MANY, HAS_ONE and MANY_MANY
The things will be much easier bearing that in mind.
I would design the tables like the following:
tbl_department
id ... AI PK
name
...
tbl_section
id ... AI PK
department_id ... FK to tbl_dpartment.id
name
...
tbl_budget
id ... AI PK
section_id ... FK to tbl_section.id
amount
...
I would not create the link table.
A Department HAS_MANY Sections, and a Section HAS_ONE Budget.
Now you will be able to access the sections and their budget like the following:
$dept = Department::model()->findByPk($id);
echo "Department = " . $dpt->name . "\n";
foreach($dept->sections as $section) {
echo "Section = " . $section->name . "\n";
echo "Budget = " . $section->budget->amount . "\n";
}