简体   繁体   English

具有preUpdate,prePersist的学说命令行插入

[英]Doctrine command line insert with preUpdate, prePersist

I can insert data in database controlled by Doctrine directly use SQL. 我可以将数据插入由Doctrine控制的数据库中,直接使用SQL。

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

However my entity has like this preUpdate() , prePersist() 但是我的实体有这样的preUpdate()prePersist()

So I want to insert with DQL, not using SQL directly. 所以我想用DQL插入,而不是直接使用SQL。

Is there any way to do this? 有什么办法吗?

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

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

So I want to insert with DQL not SQL directly. 所以我想直接用DQL而不是SQL插入。

While a command exist for DQL queries ( doctrine:query:dql ), DQL does not support INSERT queries, as you can see in the docs . 尽管存在用于DQL查询的命令( doctrine:query:dql ),但是DQL不支持INSERT查询,如您在docs中所见。

Your best option would be would be to write your own console command , inject the entity manager, and create and persist the entity there. 最好的选择是编写自己的控制台命令 ,注入实体管理器,并在那里创建并保留实体。

A very simple command would go something like this: 一个非常简单的命令将如下所示:

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();

    }
}

Which you would call console foo:entity:create . 您将其称为console foo:entity:create

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM