unique slugs with multi entities in symfony2

て烟熏妆下的殇ゞ 提交于 2019-12-08 13:43:33

问题


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?


回答1:


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;
}



回答2:


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();
}


来源:https://stackoverflow.com/questions/10968300/unique-slugs-with-multi-entities-in-symfony2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!