php - 带有 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;
}
解决方案
所以我想直接用 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
.
推荐阅读
- bash - bash 脚本在获取时会产生不同的结果
- ios - 如何从子类化 UIButton 切换隐藏 imageView
- r - 根据数据框R中另一列中的值复制值
- javascript - 为什么 texfield 的参与会以这种方式 textfield.value 起作用,而另一次我必须使用 $("#textfield").val()
- angular - 在本地使用 pdftron webviewer 服务器时无法加载 pdf 文件
- vue.js - Vuex 模块中的 import 和 module.exports 显示 Uncaught TypeError: Cannot assign to read only property 'exports' of object
- python - Python3逻辑左移
- three.js - THREE.js 中的透明点在某种程度上不透明
- android - 通过向上拖动按钮向上滑动底页(android)
- node.js - webpack 需要表达式缺少模块