Ale*_*anz 8 php doctrine symfony doctrine-orm
我想在我的学说实体中增加一个值.
目前我正是这样做的.
$file->setDownloadCounter($file->getDownloadCounter() + 1);
$em = $this->getDoctrine()->getManager();
$em->persist($fileVersion);
$em->flush();
Run Code Online (Sandbox Code Playgroud)
有没有办法在学说中执行这样的事情:
UPDATE file SET downloadCounter = downloadCounter + 1 WHERE id = 1
Run Code Online (Sandbox Code Playgroud)
编辑:
上面的学说示例中的问题是加载和刷新之间是其他人可以下载文件的时间,因此计数器不正确.
您还可以在实体存储库中执行以下操作:
return $this
->createQueryBuilder('f')
->update($this->getEntityName(), 'f')
->set('f.downloadCounter', $file->getDownloadCounter() + 1)
->where('f.id = :id')->setParameter('id', $file->getId())
->getQuery()
->execute();
Run Code Online (Sandbox Code Playgroud)
或者使用DQL:
$em = $this->getDoctrine()->getManager();
$query = $em->createQuery(
'UPDATE YourBundle:File f
SET f.downloadCounter = :downloadCounter'
)->setParameter('downloadCounter', $file->getDownloadCounter() + 1);
Run Code Online (Sandbox Code Playgroud)
或者通过简化的DQL:
$em = $this->getDoctrine()->getManager();
$query = $em->createQuery(
'UPDATE YourBundle:File f
SET f.downloadCounter = f.downloadCounter + 1'
);
Run Code Online (Sandbox Code Playgroud)
这些解决方案的缺点是:如果您的实体已经加载,它将具有先前的计数而不是递增的计数.
你做的方式非常好,但更好的方法是为你的实体添加一个增量方法.