unique slugs with multi entities in symfony2

2019-06-12 05:10发布

I have a small symfony2 application where a user can create pages. Each page should be accessible via the route /{user_slug}/{page_slug}. I have the entities user and page and I use the sluggable behavior for both entities. In order to find the correct page the combination of user_slug and page_slug has to be unique.

What is the best way to check that the combination of user_slug and page_slug is uniqe?

标签: symfony slug
2条回答
爷、活的狠高调
2楼-- · 2019-06-12 05:41

Try this in your prepository:

public function findByUsernameAndSlug($username, $slug)
{
    $em = $this->getEntityManager();
    $query = $em->createQuery("
        SELECT g
        FROM Acme\PagesBundle\Entity\Page p
        JOIN p.owner u
        WHERE u.username = :username
        AND p.slug = :slug
    ")
            ->setParameter('username', $username)
            ->setParameter('slug', $slug);

    foreach ($query->getResult() as $goal) {
        return $goal;
    }

    return null;
}
查看更多
叛逆
3楼-- · 2019-06-12 06:06

Before you persist the entity in your service-layer check whether given combination of user and page slug are unique, if not modify the page slug (append -2 or something like that) or throw an exception:

public function persistPage(Page $page) {
    $userSlug = $page->getUser()->getSlug();
    $pageSlug = $page->getSlug();

    if ($this->pagesRepository->findOneBySlugs($userSlug, $pageSlug) != null) {
        // given combination already exists
        throw new NonUniqueNameException(..);
        // or modify the slug
        $page->setSlug($page->getSlug() . '-2');
        return $this->persistPage($page);
    }

    return $this->em->persist($page);
}

// PagesRepository::findOneBySlugs($userSlug, $pageSlug)
public function findOneBySlugs($userSlug, $pageSlug) {
    $query = $this->em->createQueryBuilder('p')
            ->addSelect('u')
            ->join('p.user', 'u')
            ->where('p.slug = :pageSlug')
            ->where('u.slug = :userSlug;)
            ->getQuery();

    $query->setParameters(combine('userSlug', 'pageSlug'));

    return $query->getSingleResult();
}
查看更多
登录 后发表回答