在这方面我真的是新手。问题是..。我有文章网站。人们可以在那里给文章打分。如果没有人评价,我可以删除文章。但如果有人给文章打分,我总是得到以下错误:
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');
}你能帮我修一下吗?提前谢谢你
编辑:这是Articles.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吗
发布于 2014-10-01 21:15:48
它确实在你得到的错误消息中说明了这一点,你有一个外键引用冲突。这意味着您正在尝试删除数据库中某处引用的行,它甚至会告诉您位置:
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
发布于 2014-10-01 22:29:31
作为@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 = ?https://stackoverflow.com/questions/26142080
复制相似问题