如何在Doctrine Symfony2中从现有数据生成slug字段

5

这是我的实体,我使用了gedmo注释。当创建新的注册信息(持续存在)时,slug正常工作,但如何从现有数据库自动生成slug文本呢?

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

你想要对这个“persisted”标识符做什么具体的事情? - miltone
1
你需要更新“name”字段 - 仅持久化实体不起作用。我认为gedmo专门监听命名字段的更改。 否则,您必须编写一个小函数来帮助您完成这个任务。 - Jason Butler
请查看此链接 https://knpuniversity.com/screencast/symfony2-ep3/doctrine-extensions#configuring-slug-to-be-set-automatically - Shairyar
手动生成 "slug" 的更多信息请参见:https://dev59.com/c3bZa4cB1Zd3GeqPEljM - Dimitry K
2个回答

5
这是一个简单的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.");
        }
    }
}

嗨,希望这可以帮助到那些遇到这个问题的人!


5

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接