从数据透视表删除项目的问题

时间:2019-06-12 07:41:55

标签: php sql

我正在oop php中构建用于学习的项目,在其中创建属性/广告,并且我有三个表,属性,照片和property_photo。我的目标是,当我单击“删除”按钮以同时删除属性以删除通过数据透视表连接到属性的那些照片时,但是当我尝试仅从属性表中删除属性并且数据透视表中的照片和ID保留在其中时数据库。我在模型中编写sql查询时遇到困难。任何帮助表示赞赏。这是我的代码:

AdModel.php

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 photos WHERE id=:id;
  DELETE FROM property_photo WHERE photo_id=:photo_id AND property_id=:property_id');
  $this->db->bind(':id', $id);
  $this->db->bind(':photo_id', $id);
  $this->db->bind(':property_id', $id);
  if ($this->db->execute()) {
    return true;
  } else {
      return false;
    }
}

AdsController.php

public function addeleteAction()
 { 
    $this->Auth->isLoggedin();
    $this->Auth->isAdmin($_SESSION['user_id']);
    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->photo)) {
                unlink('public/photos/' . $photo->photo);
              }
            }
            redirect('ads/index');
          }
          echo "User is not found!!!";
     } 
 }

1 个答案:

答案 0 :(得分:1)

首先从照片中删除

DELETE FROM photos 
where photos.id in (select photos.id FROM photos join property_photo   
where property_photo.property_id = :property_id);

之后:

DELETE FROM property_photo WHERE property_id=:property_id