mysql PDO ON DELETE CASCADE - 不工作

时间:2016-11-14 15:46:21

标签: php mysql pdo

我已经看到我的问题可能已经有了答案,并且“在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;  
}

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

show create table recipes:

| 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 |

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

谢谢

1 个答案:

答案 0 :(得分:2)

你的外键关系倒退了。 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
);

您这样做,删除附件会删除配方。