【问题标题】:Problem with deleting items from pivot table从数据透视表中删除项目的问题
【发布时间】:2019-06-12 07:41:55
【问题描述】:

我正在 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!!!";
     } 
 }

【问题讨论】:

  • 你必须描述你的模型,否则将很难帮助你。
  • @SamuelTeixeira 你需要什么信息,因为我的模型很大,我不知道该放什么相关的代码。
  • 照片、property_photo 和 properties 之间的 FK 或关系。
  • 照片(id、名称、扩展名、created_at、updated_at)、property_photo(id、property_id、photo_id)、属性(id、标题、描述、type_of_property、use_of_the_property、正交、位置)。

标签: php sql


【解决方案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

【讨论】:

  • 现在我收到此错误 'Invalid parameter number: number of bound variables does not match number of tokens' 。我知道这是下面的 bind() 查询的问题,我只是无法正确处理。你能帮帮我吗?
  • 您是否删除了其他绑定?现在你只需要 $this->db->bind(':property_id', $id);不是吗?
  • 是的,我就是这样做的,现在它说我有语法错误或访问冲突: 1064 您的 SQL 语法有错误;检查与您的 MariaDB 服务器版本相对应的手册,以了解在“INNER JOIN property_photo on (property_photo.photo_id=photos.id) WHERE property_”附近使用的正确语法,我似乎找不到错误
  • mariadb.com/kb/en/library/join-syntax 这是您的数据库语法中的错误,请尝试仅使用连接,而不是内部连接
猜你喜欢
  • 2021-10-23
  • 2018-11-18
  • 1970-01-01
  • 1970-01-01
  • 2021-06-03
  • 2012-04-02
  • 1970-01-01
  • 1970-01-01
  • 2011-09-07
相关资源
最近更新 更多