我使用了doctrine和sf2,我对slug扩展有疑问: 有没有办法在冲洗之前生成它?
假设我有一个品牌实体:
/**
* Brand
*
* @ORM\Table(indexes={@ORM\Index(name="name_idx", columns={"name"})})
* @ORM\Entity(repositoryClass="Shoesalley\Bundle\CoreBundle\Entity\BrandRepository")
*/
class Brand
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="name", type="string", length=255)
*/
private $name;
/**
* @var string
*
* @Gedmo\Slug(fields={"name"})
* @ORM\Column(length=128, unique=true)
*/
private $slug;
}
// getters and setters ...
如果我这样做,我得到2个不同的slugs:test和test_1
$brand=new Brand();
$brand->setName('test');
$em->persist($brand);
$brand2=new Brand();
$brand2->setName('Test');
$em->persist($brand2);
目标是找到目标slug已经存在且只有1个DB Entry。
我不能使用find()而没有生成的slug,所以有人有想法吗?
主要观点是这样的,但我不知道如何实现它:
$brand=new Brand();
$brand->setName('test');
$slug = $brand->getSlug();
if( $oBrand = $em->getRepository("DemoBundle:Brand")->findOneBySlug($slug)){
$brand = $oBrand;
}
$em->persist($brand);
非常感谢你的帮助。
答案 0 :(得分:-1)
我认为你在解决方案中使用正确的逻辑;你可能需要注意一些小故障:
$brand = new Brand();
$brand->setName('test');
$slug = $brand->getSlug();
// Is getSlug() going to work before persist ?
// If not, you'll have to "simulate" the generation of a slug
// to obtain a string equivalent to that slug
$obrand = $em->getRepository("DemoBundle:Brand")->findOneBySlug($slug);
if(empty($obrand) { // empty, or is_null, depends on what your orm returns when it finds nothing
$em->persist(brand);
} else {
echo('Slug ' . $brand->getSlug() . ' is already in use !');
}