How to delete items from from pivot table and main table at the same time

Viewed 39

I am working on a cms for properties/ads in oop php for learning purposes. I have a gallery of photos for each property/ad and three tables.

properties (id, location, price)

property_photo (id, property_id, photo_id)

photos (id, name, extension)

I am trying when click on button delete where I delete properties, that it automatically deletes photos in property_photo and photos table that are connected to those properties, and also to delete them in my project folder. Currently I am able to delete properties from properties table and from property_photo table, but I am unable to delete those photos from photos table and in my project folder. Any help is appreciated. Here is my code.

AdModel:

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();
} 

AdsController:

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!!!";
     } 
 }
0 Answers
Related