首页 > 解决方案 > Symfony 3 修改 slug gedmo 注释

问题描述

我的实体中有一个字段:

/**
  * slug field
  *
  * @Gedmo\Slug(fields={"name"})
  * @ORM\Column(type="string", length=255, unique=true)
  *
  * @var string
  */
 private $slug;

现在我想修改这个字段以从两个字段中生成 slug。

/**
  * slug field
  *
  * @Gedmo\Slug(fields={"id", "name"})
  * @ORM\Column(type="string", length=255, unique=true)
  *
  * @var string
  */
  private $slug;

但是当我保存这个更改时,它仍然只从字段“名称”中产生 slug。如何保存此注释更改?

标签: symfonyannotationsslug

解决方案


您是否尝试过它是否适用于新实体?更改配置后,旧的 slug 不会自动更新。您必须取消设置所有现有实体的 slug 并再次保存它们以生成新的 slug。我用一个命令来做到这一点:

<?php
namespace AppBundle\Command;

use AppBundle\Entity\YourEntityClass;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;

/**
 * Generates slugs again
 */
class UpdateSlugsCommand extends ContainerAwareCommand
{
    protected function configure()
    {
        $this
            ->setName('appbundle:update-slugs')
            ->setDescription('generate new slugs')
            ->setHelp('needed after changing the config');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $em = $this->getContainer()->get('doctrine')->getEntityManager();

        $entities = $em->getRepository(YourEntityClass::class)->findAll();
        foreach ($entities as $entity) {
            // unset slug to generate a new one
            $entity->setSlug(null);
            $em->persist($entity);
        }
        $em->flush();
    }
}

推荐阅读