外键违规:7 ERROR

时间:2014-10-01 13:05:05

标签: php mysql foreign-keys

我真的是新手。事情是......我有文章网站。人们可以评论那里的文章。如果没人评价,我可以删除文章。但如果有人评价文章,我会不断收到以下错误:

PDOException: SQLSTATE[23503]: Foreign key violation: 7 ERROR:  update or delete on table "article" violates foreign key constraint "article_rating_item_id_fkey" on table "article_ratings"
DETAIL:  Key (id)=(xxxx) is still referenced from table "article_ratings". in /libs/Nette/loader.php:3515  @  http://www.xxxxxx/admin/articleedit/3578?do=deletearticle  @@  exception-2014-09-29-18-14-37-b625334b3e569cb7661f1704256874c1.htm

当我检查该文件时,有以下代码:

public function handleDeletearticle($id)
        {
            $article = $this->context->createArticles()->get($id);
            $this->context->createArticles()->where("id", $id)->delete();
            $this->flashMessage('Done', 'success');
            $this->redirect('Admin:articles');
        }

你能帮我解决一下吗?提前谢谢

编辑:这就是它看起来像Article.php

    public function selectArticleWithRating($slug)
{
    $article = $this->query("Select article.*, COUNT(rating.id) AS plus, COUNT(rating2.id) AS minus, \"user\".avatar, \"user\".username
     FROM article
     LEFT JOIN rating AS rating ON rating.item_id=article.id and rating.type='article' and rating.rate=1
     LEFT JOIN rating AS rating2 ON rating2.item_id=article.id and rating2.type='article' and rating2.rate=0
     LEFT JOIN \"user\" ON \"user\".id=article.user_id
     WHERE slug='$slug'
     GROUP BY article.id, \"user\".id");

    return $article;
}

不应该有article_ratings吗?

2 个答案:

答案 0 :(得分:1)

它确实在您收到的错误消息中这样说,您有外键引用违规。这意味着您试图删除在数据库中某处引用的行,它甚至会告诉您:

is still referenced from table "article_ratings"

您也可以使用ON DELETE CASCADE删除引荐行 http://www.mysqltutorial.org/mysql-on-delete-cascade/

有一个问题涉及SO:MySQL on delete cascade. Test Example

这里有一个很好的解释:https://dba.stackexchange.com/questions/44956/good-explanation-of-cascade-on-delete-update-behavior

编辑:关于Postgres:

CREATE TABLE order_items (
    product_no integer REFERENCES products ON DELETE RESTRICT,
    order_id integer REFERENCES orders ON DELETE CASCADE,
    quantity integer,
    PRIMARY KEY (product_no, order_id)
);

http://www.postgresql.org/docs/9.3/static/ddl-constraints.html

答案 1 :(得分:0)

作为@hebron给出的答案的另一个选项,它依赖于更改外键级联删除行为,您可能会发现它在代码中更直接和易懂(即不依赖于"隐藏"数据库行为)删除连接。

DELETE articles, article_ratings
FROM articles
LEFT JOIN article_ratings
  ON articles.id = article_ratings.article_id /* or whatever your foreign key name is */
WHERE articles.id = ?