简体   繁体   中英

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.

If a row in ticketUse exists which always has combination with a row in Lesson.

When I try to delete Lesson row '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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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