捕获 symfony 和原则中的完整性约束错误

发布于 2024-11-25 11:32:04 字数 602 浏览 2 评论 0原文

我有两张表,分别是: 类别:

|id | cat_name  |
| 1 | nameone   |
| 2 | nametwo   |   
| 3 | namethree |

新闻:

| id | id_cat | title    |
| 1  | 1      | title1 |
| 2  | 2      | title2 |
| 3  | 3      | title3 |
| 4  | 3      | title4 |
| 5  | 3      | title5 |

我使用 doctrine:generate-module 后端类别类别,并且我有一个带有 executeEdit、更新等的列表类别。如果我删除类别 id 3 - namethird,那么我得到以下错误

SQLSTATE[23000]:违反完整性约束:1451 无法删除或 更新父行:外键约束失败。

如何确保如果删除类别 3,则类别 3 的所有新闻都会移至类别 2,例如不会出现错误?怎么能抓住这个?

I have two tables which are:
Category:

|id | cat_name  |
| 1 | nameone   |
| 2 | nametwo   |   
| 3 | namethree |

News:

| id | id_cat | title    |
| 1  | 1      | title1 |
| 2  | 2      | title2 |
| 3  | 3      | title3 |
| 4  | 3      | title4 |
| 5  | 3      | title5 |

i use doctrine:generate-module backend category Category and i have a list Category with executeEdit, Update etc. If i delete Category id 3 - namethree then I get the following error

SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or
update a parent row: a foreign key constraint fails .

How can I make sure that if I delete Category 3 then all News for Category 3 are moved to Category 2 for example without an error? How can catch this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

一杯敬自由 2024-12-02 11:32:04

您必须为 News 配置表架构,以使用 ON DELETE 处理外键更改:“设置为 null”、“设置为默认值”或“设置为具体值”,或“删除”。不过,不确定您是否可以灵活地执行此操作,但如果您考虑一下,那就太疯狂了:您拥有引用完整性正是因为您希望严格执行您的关系。如果删除类别行,则随机更改它们将完全与此相反。

更好最好自己正确处理这个问题,首先更新要修改的行。

UPDATE News SET id_cat = 2 WHERE id_cat = 3;
DELETE FROM Category WHERE id = 3;

(我不知道适当的 Symfony/Doctrine 方法会影响这一点。)

您的可用选项取决于您的数据库。您始终可以说ON DELETE CASCADE删除所有相关行;其他选项可能对您可用,也可能不可用。

You have to configure your table schema for News to handle foreign key changes with ON DELETE: Either "set to null", or "set to default", or "set to specific value", or "delete". Not sure if you can do this variably, though, but if you think about it that'd be insane: You have referential integrity precisely because you want your relations to be strictly enforced. Randomly changing them if you delete a category row would go completely counter to that.

Much better to handle this correctly yourself by first UPDATEing the to-be-modified rows.

UPDATE News SET id_cat = 2 WHERE id_cat = 3;
DELETE FROM Category WHERE id = 3;

(I don't know the appropriate Symfony/Doctrine method to affect this.)

Your available options depend on your database. You can always say ON DELETE CASCADE to delete all dependent rows; other options may or may not be available to you.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文