简体   繁体   English

如何与外键关系一起删除两行

[英]How to delete two rows together with foreign key relationship

I have two tables and these two have relationship like 我有两个表,这两个表有关系

class Lesson
{
/**
 * @var integer
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;



class TicketUse  
{
/**
 *
 * @ORM\ManyToOne(targetEntity="Acme\UserBundle\Entity\Lesson")
 * @ORM\JoinColumn(name="lessonId", referencedColumnName="id")
 */

private $lessonId;

These two tables relation ships are. 这两个表关系是船。

If a row in Lesson is exist,a row in ticketUse exists or doesn't exist. 如果存在Lesson中的行,则ticketUse中的行存在或不存在。

If a row in ticketUse exists which always has combination with a row in Lesson. 如果存在ticketUse中的一行,该行始终与Lesson中的行组合。

When I try to delete Lesson row 'DELETE FROM Lesson WHERE id = 1' 当我尝试删除课程行'DELETE FROM Lesson WHERE id = 1'时

it shows error. 它显示错误。

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

I want to delete TicketUse automatically,when I delete Lesson. 我想删除Lesson时自动删除TicketUse。

Is there good way to delete both together? 有没有好的方法可以同时删除它们?

I have two write delete sentences for each? 我有两个写删除句子?

for your FOREIGN KEY relationship, add ON UPDATE CASCADE . 对于您的FOREIGN KEY关系,添加ON UPDATE CASCADE
then you will be able to delete according to your needs. 然后你就可以根据自己的需要删除了。
When you will delete the parent the change will be automatically reflected to the child. 当您删除父级时,更改将自动反映给孩子。

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

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