我有一个实体。
My'Bundle'Entity'Service:
type: entity
table: SERVICE
fields:
idService:
id: true
type: integer
unsigned: false
nullable: false
column: ID_SERVICE
generator:
strategy: IDENTITY
codeService:
type: string
length: 5
fixed: false
nullable: false
column: CODE_SERVICE
dateCreation:
type: date
nullable: false
column: DATE_CREATION
dateModification:
type: date
nullable: false
column: DATE_MODIFICATION
在我的数据库中,我有一个 BEFORE INSERT 触发器,用于设置 dateCreation 和 dateModification。
我想让他做他的工作,但是当我坚持一个新实体时,我收到这个SQL错误:
An exception occurred while executing 'INSERT INTO SERVICE (CODE_SERVICE, DATE_CREATION, DATE_MODIFICATION) VALUES (?, ?, ?)' with params ["test", null, null]:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'DATE_CREATION' cannot be null
有没有办法做到这一点?我知道触发器很糟糕,但我别无选择......
这是触发器,它有效:
CREATE TRIGGER `SERVICE_BI_TG` BEFORE INSERT ON `SERVICE` FOR EACH ROW BEGIN
BEGIN
SET NEW.DATE_CREATION=NOW();
SET NEW.DATE_MODIFICATION=NOW();
END
问题是我在 INSERT 或 UPDATE 上设置了一些其他字段,例如其他表上的一些外键和一些 UPDATE,我为我的帖子简化了它。
您不需要在数据库中为此定义触发器。
对于 dateCreation,您可以在实体构造函数中初始化它:
public function __construct()
{
$this->dateCreation = new 'DateTime('now');
}
和日期修改您需要在预更新事件触发的方法:
use Doctrine'ORM'Mapping as ORM;
/**
* @ORM'HasLifecycleCallbacks
*/
class myEntity{
/**
* @var 'DateTime
* @ORM'Column(name="date_modification", type="datetime")
*/
private $this->dateModification;
/**
* @ORM'PreUpdate
*/
public function incremenDateModification() {
$this->dateModification = new 'DateTime();
}
}