繁体   English   中英

mysql PDO删除级联-不起作用

[英]mysql PDO ON DELETE CASCADE - not working

我已经看到我的问题可能已经有了答案,并且“在mysql中,关于删除级联不起作用”似乎更相似.....但我看不到任何有关该帖子对我有用的建议。

问题是,当我删除配方时,我希望它的附件也被删除(好吧,一步一步,此刻,我只是想从mysql表中删除它,而不是从存储它的文件夹中删除它)。

在我在这里发布了类似的问题之后,但是关于如何创建mysql触发器,我设置了外键,并在删除级联上进行了操作,因此我虽然在配方被删除的同时也删除了附件,但是附件完全没有任何反应。 ... 我究竟做错了什么?

在每个食谱旁边,我都有一个删除它的按钮:

echo '<a class="toLink" href="delete_recipe.php?id=' . $recipe['id'] . '" title="delete recipe"  onclick="return confirm(\'Are you sure you want to delete this recipe?\');">Delete recipe</a>';  

在delete_recipe.php中:

<?php require 'includes/functions.php';

 $recipeId = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT);     
      if(delete_recipe($recipeId) == true) {
         header('Location: index.php');
         exit;
      } else {
           $error_message = "Could not delete recipe";
      }

在functions.php中:

function delete_recipe($recipe_id = ':recipe_id') {
          include 'db_connection.php';
    try {
        $sql = "DELETE FROM recipes ";
        $sql .= "WHERE id =:recipe_id ";
        $sql .= "LIMIT 1";

        $results = $conn->prepare($sql);
        $results->bindParam(':recipe_id', $recipe_id, PDO::PARAM_INT);

    if($results->execute()) {
      echo '1 row has been removed';     
    }

    $conn = null;

    } catch(PDOException $e) {
        echo 'Error: ' . $e->getMessage() . '<br />';
        return false;
    }

    return true;  
}

我想我已经设置了外键并正确地“级联删除” .....如果我这样做:

显示创建表食谱:

| recipes | CREATE TABLE `recipes` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(100) NOT NULL,
  `attachment_id` int(11) NOT NULL,
  `chef_id` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `fk_recipes_attachments1_idx` (`attachment_id`),
  KEY `fk_recipes_chefs1_idx` (`chef_id`),
  CONSTRAINT `fk_recipes_attachments1` FOREIGN KEY (`attachment_id`) REFERENCES `attachments` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `fk_recipes_chefs1` FOREIGN KEY (`chef_id`) REFERENCES `chefs` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8 |

显示创建表附件:

| attachments | CREATE TABLE `attachments` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `attachment_path` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8 |

知道为什么它不从属于我要删除的配方的附件表中删除附件吗?

谢谢

您的外键关系倒退了。 attachments表应具有一个recipe_id列,并且该列应该是recipes的外键。

CREATE TABLE `attachments` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `attachment_path` varchar(255) NOT NULL,
    `recipe_id` INT(11),
    PRIMARY KEY (`id`),
    FOREIGN KEY (`recipe_id`) REFERENCES `recipe` (`id`) ON DELETE CASCADE
);

删除附件的方式将删除配方。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM