I have changed the schema of a Symfony application by transforming a one-to-many relationship to a many-to-many relationship between a Sample
model and a Collector
model. The Sample
model had a collector_id
foreign key and now there is an intermediate model (SampleCollectors
) with two foreign keys: sample_id
and collector_id
.
Sample:
columns:
id: { type: integer, primary: true, autoincrement: true }
...
collector_id: ... # This column is removed
...
relations:
...
Collectors: { foreignAlias: Collectors, class: Collector, local: sample_id, foreign: collector_id, refClass: SampleCollectors }
Collector:
columns:
id: { type: integer, primary: true, autoincrement: true }
...
relations:
Samples: { foreignAlias: Samples, class: Sample, local: collector_id, foreign: sample_id, refClass: SampleCollectors }
SampleCollectors:
columns:
sample_id: { type: integer, primary: true }
collector_id: { type: integer, primary: true }
relations:
Sample: { onDelete: cascade }
I have edited the schema.yml file
like above and executed the following tasks:
php symfony doc:generate-migrations-diff
php symfony doc:build --all-classes
which has rebuilt every involved model/form/filter and created two migration classes.
Since the database is already in production-mode, I have tuned the migration classes to move the foreign key of the one-to-many relationship (Sample
.collector_id
) to the many-to-many intermediate table (SampleCollectors
.collector_id
):
public function preUp() {
$sampleTable = Doctrine_Core::getTable('Sample');
// I do this because collector_id has disappeared after model regeneration.
$sampleTable->setColumn('collector_id', 'integer', null, array('type' => 'integer'));
$this->samples = $sampleTable->findAll()->toArray();
}
public function up() {
// ...
$this->removeColumn('sample', 'collector_id');
// ...
$this->createTable('sample_collectors', array(...), array(
'type' => 'INNODB',
'primary' => array(0 => 'sample_id', 1 => 'collector_id'),
...));
}
public function postUp() {
foreach ( $this->samples as $sample ) {
$sampleCollector = new SampleCollectors();
$sampleCollector->setSampleId($sample['id']);
$sampleCollector->setCollectorId($sample['collector_id']);
$sampleCollector->trySave();
}
}
I have migrated the database and everything went apparently well.
But now that I'm updating the controllers, views, etc., Doctrine still tries to retrieve the collector_id
column from Sample, instead of navigating through the many-to-many relationship.
Since the Sample
model does not store a reference to it anymore, why does Doctrine insist on that? I checked the BaseSample
class and it does not have a hasColumn()
method setting a column collector_id
. BTW, I clear the cache as well.
Thanks!