首页 > 解决方案 > 如何同时从数据透视表和主表中删除项目

问题描述

为了学习目的,我正在为 oop php 中的属性/广告开发一个 cms。我有每个属性/广告的照片库和三张桌子。

properties (id, location, price)

property_photo (id, property_id, photo_id)

photos (id, name, extension)

我正在尝试单击删除属性的按钮删除,它会自动删除连接到这些属性的 property_photo 和照片表中的照片,并在我的项目文件夹中删除它们。目前我可以从属性表和 property_photo 表中删除属性,但我无法从照片表和我的项目文件夹中删除这些照片。任何帮助表示赞赏。这是我的代码。

广告模型:

public function deleteProperty($id)
{
  $this->db->query('DELETE FROM properties WHERE id=:id');
  $this->db->bind(':id', $id);
  if ($this->db->execute()) {
    return true;
  }
  else {
    return false;
  }
}

public function deletePropertyPhoto($id)
{
  $this->db->query('DELETE FROM property_photo WHERE property_id=:property_id');
  $this->db->bind(':property_id', $id);
  $this->db->query('DELETE FROM photos WHERE id=(SELECT photo_id FROM property_photo WHERE property_id=:property_id)');
  $this->db->bind(':property_id', $id);
  $this->db->execute();
} 

广告控制器:

public function addeleteAction()
 { 
    $userinfo = $this->Auth->Auth(['admin', 'moderator']);
    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
        $_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
        $_GET = filter_input_array(INPUT_GET, FILTER_SANITIZE_STRING);
        $this->Auth->isSet($_GET['id'], "ads/index");

          if ($this->AdModel->deleteProperty($_GET['id'])) {
            $photo = $this->AdModel->deletePropertyPhoto($_GET['id']);
            if ($photo != false) {
              if (file_exists('public/photos/' . $photo->name . '.' . $photo->extension)) {
                unlink('public/photos/' . $photo->name . '.' . $photo->extension);
              }
            }
            redirect('ads/index');
          }
          echo "Property is not found!!!";
     } 
 }

标签: phpsqlpdo

解决方案


推荐阅读