I have an application with 3 tables:
- appgroups
- id
- name
- apptestgroups
- id
- name
- id_appgroup (foreign key to appgroups on field id)
- applications
- id
- name
- id_apptestgroup (foreign key to apptestgroups on field id)
This means that an application belongs to one apptestgroup and an apptestgroup belongs to an appgroup
I want change the relations/foreign keys so that one application belongs to a appgroup. To do this i need to create a migration to do the following changes:
[list=1]
[*]Change the id_apptestgroup to id_appgroup in table {{applications}}
[*]Update the id_appgroup in table {{applications}} with the values in the id_appgroup in table {{apptestgroups}}
[/list]
I managed to find a way to do the first point.
To do this i need to removed the foreignkey first and then recreate it at the end. No problem
The problem is the second point.
I believe i need to
-
Create a model for the table before the id_apptestgroup change to id_appgroup
-
Do a findAll with that model
-
Update every new field to the id_appgroup from the previous relation
This is the code i’m using:
$applications_before = m110718_051216_change_application_parent_to_appgroup_ApplicationsTable::model()->with('idApptestgroup','idApptestgroup.idAppgroup','idApptestgroup.idAppgroup.idClient')->findAll();
$this->dropForeignKey("FK_apptestgroup", "{{applications}}");
$this->renameColumn("{{applications}}", "id_apptestgroup","id_appgroup");
echo " > found " . count($applications_before) . " applications\n";
foreach ($applications_before as $app) {
echo " > processing application " . $app->name . "\n";
if($app->idApptestgroup !== null) {
if($app->idApptestgroup->idAppgroup !== null ) {
$model = Applications::model()->findByPk($app->id);
echo " > saving appgroup id " . $app->idApptestgroup->id_appgroup . "\n";
$model->id_appgroup=$app->idApptestgroup->id_appgroup;
$model->save();
}
}
}
$this->addForeignKey("FK_appgroup", "{{applications}}", "id_appgroup", "{{appgroups}}", "id","NO ACTION","NO ACTION");
The problem is when i do the assignment it complains the id_appgroup attribute does not exist
Doing a var_dump i noticed that the $model variable is assigned the old attributes and relations
I believe this happens because both models m110718_051216_change_application_parent_to_appgroup_ApplicationsTable and Applications use the same table.
I hope i was clear explaining my problem.
Please ask me if you some doubts.