我刚刚创建了一个从我的数据库中删除实体记录的操作。 行动是:
public function eliminaricettaAction($id)
{
$em = $this->getDoctrine()->getManager();
$ricetta = $em->getRepository('AppBundle:Ricette')->find($id);
$em->remove($ricetta);
$em->flush();
return $this->render('adminarea/gestionericette.html.twig', array(
'base_dir' => realpath($this->container->getParameter('kernel.root_dir') . '/..'),
));
}
我得到的错误是:
警告:unlink():没有这样的文件或目录
所以我认为问题在于它自身的实体,特别是在这种代码的和平中:
/**
* @ORM\PreRemove()
*/
public function removeImage()
{
unlink($this->getFullImagePath());
rmdir($this->getUploadRootDir());
}
我做错了什么?
答案 0 :(得分:4)
您正在尝试删除不存在的文件。
在尝试删除文件之前,您应该确保它们存在。确认您实际从$this->getFullImagePath()
返回文件路径,并使用file_exists()确认路径中的文件存在。
你可以像这样实现它:
public function removeImage()
{
if($file = $this->getFullImagePath() && file_exists($file)) {
unlink($file);
rmdir($this->getUploadRootDir());
}
}
理想情况下,您还要检查$this->getUploadRootDir()
是否返回一个值并且该目录是否存在且在尝试删除之前不为空;但您也可以考虑每次删除文件时是否真的需要删除uploadRootDir
。 (你是否应该完全是一个单独的问题。)
答案 1 :(得分:0)
首先,您应检查文件是否存在,@jbafford's answer对此有好处。
但接下来你必须检查uploadRootDir
是否为空,因为你无法删除非空的目录。
$scannedDir = $this->getUploadRootDir();
if (is_dir($scannedDir)) {
$entries = scandir($entries);
if (count($entries) === 2) {
// When you have 2 entries it means you have "." and ".."
rmdir($scannedDir);
} else {
// Directory is not empty, so take care about this.
}
} else {
// Directory does not exist so you may throw an exception or do something else.
}