通常,当您使用Doctrine实现实体时,您将其明确映射到表:
<?php
/**
* @Entity
* @Table(name="message")
*/
class Message
{
//...
}
或者你回复doctrine来隐式地将你的类名映射到一个表...我有几个在schema中相同的表,但是我不希望每次都重新创建这个类...那么在运行时(动态)我想相应地更改表名。
我从哪里开始,或者我会考虑什么来覆盖以实现这个奇怪的要求?
答案 0 :(得分:2)
Surprisingly (to me), the solution is very simple. All you have to do is to get the ClassMetadata
of your entity and change the name of the table it maps to:
/** @var EntityManager $em */
$class = $em->getClassMetadata('Message');
$class->setPrimaryTable(['name' => 'message_23']);
You need to be careful and do not change the table name after you have loaded some entities of type Message
and changed them. It's a big chance it will either produce SQL errors on saving (because of table constraints, for example), if you are lucky or it will modify the wrong row (from the new table).
I suggest the following workflow:
The step #5 (detach the entities from the entity manager) is useful even if you don't change or don't save the entities. It allows the entity manager use less memory and work faster.
This is just one of the many methods you can use to dynamically set/change the mapping. Take a look at the documentation of class ClassMetadata for the rest of them. You can find more inspiration in the documentation page of the PHP mapping.