I added an auto-update timestamp to an entity like in this blog post and it works just fine.
Here is the code snippet:
#[Entity]
class Article
{
#[Column(type: "datetime",
columnDefinition: "TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP",
insertable: false,
updatable: false,
generated: "ALWAYS")]
public $created;
}
The first time I run php bin/console make:migration
the correct migration is generated:
$this->addSql('ALTER TABLE article ADD created TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP');
This works just fine and any DB update now updates created
. However, this is also where the problems begin. Whenever I make another migration now, it tries to apply the same changes again:
$this->addSql('ALTER TABLE article CHANGE created created TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP');
How can this be, and does anyone know how to fix this?
Thank you very much for your input, I really appreciate it.
2
Answers
So I didn't figure out why this happens. But the solution to this problem is to check if the property in question already exists, and then ignore it when diffing: https://www.liip.ch/en/blog/doctrine-and-generated-columns
Edit:
So, the classes used in the blog article above are deprecated and I had to dig a little deeper into Doctrine on how to exclude specific table columns.
I performed the following steps, and it works like a charm:
SchemaManagerFactory
MySQLSchemaManager
(at least if you use MySQL, that is)Comparator
schema_manager_factory: doctrine.dbal.default_schema_manager_factory
to my entries inconnections
indoctrine.yaml
doctrine.dbal.default_schema_manager_factory
inservices.yaml
Here is some example code to make this more clear.
Doctrine sees that your actual column has a default value while none is defined in its mapping’s
options
(ignoring yourcolumnDefinition
). Thus, it decides it needs to generate an ALTER migration, and when doing so it does take into account yourcolumnDefinition
.Set
options: ["default" => "CURRENT_TIMESTAMP"]
in the column attributes:Alternatively, if you’re only changing entries in this table through Doctrine, you can use Doctrine lifecycle events to keep created/updated timestamp fields up-to-date.