在应用中有的时候难免要进行一些删除记录操作,但是这个时候如果有外键关联,并且不想把关联数据删除掉就很麻烦。
解决方法是可以采用symfony自带的软删除功能
步骤如下:
1:通过composer要安装stof这个bundle
"require": {
"stof/doctrine-extensions-bundle": "dev-master",
...
2:在app kernel中注册这个bundle
public function registerBundles()
{
$bundles = array(
new Stof\DoctrineExtensionsBundle\StofDoctrineExtensionsBundle(),
}
3:在config文件中增加配置
在doctrine的orm下增加filters部分
orm: auto_generate_proxy_classes: "%kernel.debug%" naming_strategy: doctrine.orm.naming_strategy.underscore auto_mapping: true filters: soft-deleteable: class: Gedmo\SoftDeleteable\Filter\SoftDeleteableFilter # Required enabled: true
stof_doctrine_extensions:
default_locale: en_US
orm:
default:
tree: true
timestampable: true # not needed: listeners are not enabled by default
softdeleteable: true
4:修改需要软删除的entity
增加引用
use Gedmo\Mapping\Annotation as Gedmo;
增加标记字段
/**
* Video
*
* @ORM\Table(name="videos")
* @ORM\Entity(repositoryClass="Tron\WebBundle\Repository\VideoRepository")
* @Gedmo\SoftDeleteable(fieldName="deletedAt", timeAware=false)//添加此行
*/
添加字段deleteat
/**
* @ORM\Column(type="datetime", nullable=true)
*/
private $deletedAt;
/**
* Get isDelete
*
* @return boolean
*/
public function getIsDelete()
{
return $this->isDelete;
}
public function getDeletedAt()
{
return $this->deletedAt;
}