首页 > 解决方案 > 带有 preUpdate、prePersist 的 Doctrine 命令行插入

问题描述

我可以直接使用 SQL 在 Doctrine 控制的数据库中插入数据。

php bin/console doctrine:query:sql \
    "INSERT INTO meta_info(app_title,enabled) VALUES('mapapp',1)"

但是我的实体有这样preUpdate()的,prePersist()

所以我想用 DQL 插入,而不是直接使用 SQL。

有没有办法做到这一点?

/**
* @ORM\PreUpdate
*/
public function preUpdate()
{
    $this->updatedAt = new \DateTime;
}
/**
* @ORM\PrePersist
*/
public function prePersist(){

    $this->createdAt = new \DateTime;
    $this->updatedAt = new \DateTime;
}

标签: phpsymfonydoctrine-ormdoctrine

解决方案


所以我想直接用 DQL 而不是 SQL 插入。

虽然存在用于 DQL 查询的命令 ( doctrine:query:dql),但 DQL 不支持查询,如您在 docsINSERT中所见。

您最好的选择是编写自己的控制台命令,注入实体管理器,并在那里创建和持久化实体。

一个非常简单的命令会是这样的:

class FooCreate extends Command {

    protected static $defaultName = 'foo:entity:create';
    /**
     * @var EntityManagerInterface
     */
    private $manager;

    public function __construct( EntityManagerInterface $manager ) {
        $this->manager = $manager;
        parent::__construct();
    }

      protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $entity = new Entity('app_title', 'enabled');
        $this->manager->persist($entity);
        $this->manager->flush();

    }
}

你会打电话给console foo:entity:create.


推荐阅读