[英]How to properly set entity update time with Doctrine?
MySQL表中的列稱為“updated_at”。 它是datetime類型,不是null。 Doctine類型也是日期時間。
CREATE TABLE `example` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`created_at` datetime NOT NULL,
`updated_at` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
Some\Bundle\Entity\Example:
type: entity
table: examples
fields:
id:
id: true
type: integer
generator:
strategy: IDENTITY
...
createdAt:
type: datetime
column: created_at
updatedAt:
type: datetime
column: updated_at
$e = new Example;
$e->setCreatedAt(new \DateTime);
$em->persist($e);
/* after this I need $e->updatedAt to be MySQL's default 0 (0000-00-00) */
$em->flush();
/* but it will throw
"Integrity constraint violation: 1048 Column 'updated_at' cannot be null"
if I won't set it in Example::__contruct()
which I don't see any reason to do
apart from complying with Doctrine shortcomings. */
如果實體在創建后沒有更新過,我不希望在此列中有任何值。
如何在不更改MySQL或Doctrine類型的情況下跳過此列或設置正確的值(因為它們是正確的)?
兩種選擇。 使用我在評論中提到的Timestampable 。 對於symfony,它集成在StofDoctrineExtensionsBundle中 。 然后,您只需將其添加到映射yaml中,並且不需要控制器,服務等中的其他代碼。
選項二:將updated_at
設置為NULL而不是NOT NULL。 NOT NULL意味着,必須有一個值(例如至少為0000-00-00)。 如果在MySQL中允許NULL值,您將達到您的考慮范圍。
Doctrine不能跳過列,使用您在元數據配置中定義的所有字段。
你應該在構造函數中設置一些默認值,空字符串適合幾乎所有類型。
它只會持久使用一次,后續的提取不會觸發構造。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.