我如何从数据库中的现有数据生成 slug 字段 - Doctrine Symfony2

How I can generate the slug field the from existing data in database - Doctrine Symfony2

这是我的实体,我使用了 gedmo 注释,当创建一个新的寄存器时(持久化)slug 工作正常但我如何从现有数据库自动生成 slug 文本

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

您必须按照 Sluggable Behavior 文档中的描述,手动选择所有没有 slug 的值并将 slug 值设置为 null。

https://github.com/Atlantic18/DoctrineExtensions/blob/master/doc/sluggable.md#regenerating-slug

这是一个简单的 Symfony 命令,用于重新生成给定 类 的所有 slug:

<?php

namespace App\Command;

use App\Entity\Foo;
use App\Entity\Bar;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class RegenerateSlugs extends Command
{
    private $doctrine;

    protected static $defaultName = "app:regenerate-slugs";

    public function __construct(ManagerRegistry $doctrine)
    {
        parent::__construct();

        $this->doctrine = $doctrine;
    }

    protected function configure(): void
    {
        $this
            ->setDescription('Regenerate the slugs for all Foo and Bar entities.')
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output): void
    {
        $manager = $this->doctrine->getManager();

        // Change the next line by your classes
        foreach ([Foo::class, Bar::class] as $class) {
            foreach ($manager->getRepository($class)->findAll() as $entity) {
                $entity->setSlug(null);
                //$entity->slug = null; // If you use public properties
            }

            $manager->flush();
            $manager->clear();

            $output->writeln("Slugs of \"$class\" updated.");
        }
    }
}

嗨,希望它能帮助遇到这个问题的人!