Doctrine onDelete 关系 SET NULL 并设置其他字段
Doctrine onDelete relation SET NULL and set other field
如何在移除教师后将 $isSuspended
也设置为 true
?
<?php
class Teacher {
/**
*@ORM\OneToMany(targetEntity="Activities", mappedBy="teacher")
*/
protected $activities;
}
class Activities {
/**
* @ORM\ManyToOne(targetEntity="Teacher", inversedBy="activities")
* @ORM\JoinColumn(name="teacher_id", referencedColumnName="id", nullable=true, onDelete="SET NULL")
*/
protected $teacher;
/**
* Activities are suspended when there is not teacher
*/
protected $isSuspended = false;
}
这部分 onDelete="SET NULL"
在数据库级别工作,因此要更改 $isSuspended
字段,您可以为 postRemove
学说事件创建侦听器。
use Doctrine\ORM\Event\LifecycleEventArgs;
public function postRemove(LifecycleEventArgs $event)
{
$entity = $event->getEntity();
if ($entity instanceof Teacher) {
foreach($entity->getActivities() as $activity) {
$activity->setIsSuspended(true);
$event->getEntityManager()->persist($activity);
}
$event->getEntityManager()->flush();
}
}
如何在移除教师后将 $isSuspended
也设置为 true
?
<?php
class Teacher {
/**
*@ORM\OneToMany(targetEntity="Activities", mappedBy="teacher")
*/
protected $activities;
}
class Activities {
/**
* @ORM\ManyToOne(targetEntity="Teacher", inversedBy="activities")
* @ORM\JoinColumn(name="teacher_id", referencedColumnName="id", nullable=true, onDelete="SET NULL")
*/
protected $teacher;
/**
* Activities are suspended when there is not teacher
*/
protected $isSuspended = false;
}
这部分 onDelete="SET NULL"
在数据库级别工作,因此要更改 $isSuspended
字段,您可以为 postRemove
学说事件创建侦听器。
use Doctrine\ORM\Event\LifecycleEventArgs;
public function postRemove(LifecycleEventArgs $event)
{
$entity = $event->getEntity();
if ($entity instanceof Teacher) {
foreach($entity->getActivities() as $activity) {
$activity->setIsSuspended(true);
$event->getEntityManager()->persist($activity);
}
$event->getEntityManager()->flush();
}
}