php – Doctrine Entity增加值(下载计数器)
发布时间:2020-12-13 13:30:55 所属栏目:PHP教程 来源:网络整理
导读:我想在我的学说实体中增加一个值. 目前我这样做. $file-setDownloadCounter($file-getDownloadCounter() + 1);$em = $this-getDoctrine()-getManager();$em-persist($fileVersion);$em-flush(); 有没有办法在学说中执行这样的事情: UPDATE file SET downloa
我想在我的学说实体中增加一个值.
目前我这样做. $file->setDownloadCounter($file->getDownloadCounter() + 1); $em = $this->getDoctrine()->getManager(); $em->persist($fileVersion); $em->flush(); 有没有办法在学说中执行这样的事情: UPDATE file SET downloadCounter = downloadCounter + 1 WHERE id = 1 编辑: 上面的学说示例中的问题是加载和刷新之间是其他人可以下载文件的时间,因此计数器不正确.
您还可以在实体存储库中执行以下操作:
return $this ->createQueryBuilder('f') ->update($this->getEntityName(),'f') ->set('f.downloadCounter',$file->getDownloadCounter() + 1) ->where('f.id = :id')->setParameter('id',$file->getId()) ->getQuery() ->execute(); 或者使用DQL: $em = $this->getDoctrine()->getManager(); $query = $em->createQuery( 'UPDATE YourBundle:File f SET f.downloadCounter = :downloadCounter' )->setParameter('downloadCounter',$file->getDownloadCounter() + 1); 或者通过简化的DQL: $em = $this->getDoctrine()->getManager(); $query = $em->createQuery( 'UPDATE YourBundle:File f SET f.downloadCounter = f.downloadCounter + 1' ); 这些解决方案的缺点是:如果您的实体已经加载,它将具有先前的计数而不是递增的计数. 你做的方式非常好,但更好的方法是为你的实体添加一个增量方法. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |