现有数据库中的 Symfony Doctrine Sluggable 扩展
Symfony Doctrine Sluggable extension in existing database
我必须在现有实体中添加一个 slug 字段来对字段进行 slugify 'name'。但是这个实体中已经有数据了,我不能删除它们。
我想创建一个控制台脚本,它可以对我所有的 'name' 字段进行 slugify。
我不知道该怎么做,因为这不是插入而是更新...
class SlugCommand extends ContainerAwareCommand
{
protected function configure()
{
$this
->setName('generate:geo:slug')
->setDescription('Slug generation for GeoBundle ');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$em = $this->getContainer()->get('doctrine')->getManager();
$regions = $em->getRepository('FMGeoBundle:Region')->findAll();
if($regions === null){
throw new Exception('No Region found');
}
foreach($regions as $region){
// ????? Generate the slug here ??
$em->persist($region);
}
$em->flush();
$output->writeln('Slugs Generated ;) ...');
}
}
我实体中的 'slug' 字段:
/**
* @var string
*
* @ORM\Column(name="slug", type="string", length=255)
* @Gedmo\Slug(fields={"name"})
*/
protected $slug;
Sluggable 扩展适用于 create 和 update 操作。因此,您可以通过将行的名称与其自身放在一起来模拟更新。
我找到了一个更简单的方法。您显然可以像那样手动设置 slug。它将使所需的领域变得混乱。
foreach ($regions as $region) {
$region->setSlug($region->getName());
$this->em->persist($region);
}
刚刚看到 Gedmo library documentation 直接回答了这个问题:
Regenerating slug
In case if you want the slug to regenerate itself based on sluggable
fields, set the slug to null.
<?php $entity = $em->find('Entity\Something', $id);
$entity->setSlug(null);
$em->persist($entity); $em->flush();
因此,在您的情况下,您只需保留实体,没有别的。因为 $slug 已经是 null.
我必须在现有实体中添加一个 slug 字段来对字段进行 slugify 'name'。但是这个实体中已经有数据了,我不能删除它们。
我想创建一个控制台脚本,它可以对我所有的 'name' 字段进行 slugify。
我不知道该怎么做,因为这不是插入而是更新...
class SlugCommand extends ContainerAwareCommand
{
protected function configure()
{
$this
->setName('generate:geo:slug')
->setDescription('Slug generation for GeoBundle ');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$em = $this->getContainer()->get('doctrine')->getManager();
$regions = $em->getRepository('FMGeoBundle:Region')->findAll();
if($regions === null){
throw new Exception('No Region found');
}
foreach($regions as $region){
// ????? Generate the slug here ??
$em->persist($region);
}
$em->flush();
$output->writeln('Slugs Generated ;) ...');
}
}
我实体中的 'slug' 字段:
/**
* @var string
*
* @ORM\Column(name="slug", type="string", length=255)
* @Gedmo\Slug(fields={"name"})
*/
protected $slug;
Sluggable 扩展适用于 create 和 update 操作。因此,您可以通过将行的名称与其自身放在一起来模拟更新。
我找到了一个更简单的方法。您显然可以像那样手动设置 slug。它将使所需的领域变得混乱。
foreach ($regions as $region) {
$region->setSlug($region->getName());
$this->em->persist($region);
}
刚刚看到 Gedmo library documentation 直接回答了这个问题:
Regenerating slug
In case if you want the slug to regenerate itself based on sluggable fields, set the slug to null.
<?php $entity = $em->find('Entity\Something', $id); $entity->setSlug(null); $em->persist($entity); $em->flush();
因此,在您的情况下,您只需保留实体,没有别的。因为 $slug 已经是 null.