doctrine2 - Doctrine swap out table at runtime -
typically when implement entity using doctrine map table explicitly:
<?php /** * @entity * @table(name="message") */ class message { //... }
or reply on doctrine implicitly map class name table...i have several tables identical in schema not wish re-create class each time...there fore @ runtime (dynamically) change table name accordingly.
where start or overriding implement odd requirement???
surprisingly (to me), solution simple. have classmetadata
of entity , change name of table maps to:
/** @var entitymanager $em */ $class = $em->getclassmetadata('message'); $class->setprimarytable(['name' => 'message_23']);
you need careful , not change table name after have loaded entities of type message
, changed them. it's big chance either produce sql errors on saving (because of table constraints, example), if lucky or modify wrong row (from new table).
i suggest following workflow:
- set desired table name;
- load entities;
- modify them @ will;
- save them;
- detach them entity manager (the method entitymanager::clear() quick way start over);
- go step 1 (i.e. repeat using table).
the step #5 (detach entities entity manager) useful if don't change or don't save entities. allows entity manager use less memory , work faster.
this 1 of many methods can use dynamically set/change mapping. take @ documentation of class classmetadata rest of them. can find more inspiration in documentation page of php mapping.
Comments
Post a Comment