在Symfony2中多实体独特的蛞蝓(unique slugs with multi entitie

2019-09-17 23:16发布

我有一个小的Symfony2应用程序,用户可以在创建页面。 每个页面应该是通过路由/ {} user_slug访问/ {} page_slug。 我有实体的用户和页面,我用两个实体sluggable行为。 为了找到正确的页面user_slug和page_slug的组合必须是唯一的。

什么是检查user_slug和page_slug的组合是潮头的最好方法?

Answer 1:

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


Answer 2:

在你坚持你的服务层实体检查是否对用户和页面蛞蝓给定组合是独一无二的,如果不修改页面蛞蝓(追加-2或类似的东西),或抛出一个异常:

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


文章来源: unique slugs with multi entities in symfony2
标签: symfony slug