【问题标题】:filtering results based on two ManyToOne relations in Symfony2基于 Symfony2 中的两个多对一关系过滤结果
【发布时间】:2015-06-05 14:11:14
【问题描述】:

在下面的示例中,$type 可以是“品牌”或“类别”,而 $slug 可以是品牌或类别。

当我想同时过滤一个类别和一个品牌的结果时,我该如何处理?

    public function getGroupAction($slug, $type = null, $grouped = true)
{

    $group = $this->getDoctrine()
        ->getRepository('AudsurShopBundle:'.$type)
        ->findOneBy(array( 'name' => $slug ))
        ->getProducts();

    return $this->render('AudsurShopBundle:Default:productOverview.html.twig', array(
            'group' => $group
        )
    );

}

【问题讨论】:

    标签: symfony doctrine many-to-one


    【解决方案1】:

    要做你想做的事,你必须使用Class table inheritance和鉴别器列的系统。

    对于您的示例,创建以下实体:

    <?php
    
    namespace ...
    
    use Doctrine\ORM\Mapping as ORM;
    
    /**
     * @ORM\Entity
     * @ORM\InheritanceType("JOINED")
     * @ORM\DiscriminatorColumn(name="discriminator", type="string")
     * @ORM\DiscriminatorMap({"category" = "Category", "brand" = "Brand"})
     */
    abstract class NameHolder
    {
        /**
         * @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;
    
        // Getters and setters
    }
    

    然后让你的 2 个实体继承这个类:

    <?php
    
    namespace ...;
    
    use Doctrine\ORM\Mapping as ORM;
    
    /**
     * FirstChild
     *
     * @ORM\Table()
     * @ORM\Entity
     */
    class Category extends NameHolder
    {
        // all methods and properties except from the "name"
    }
    

    和:

    <?php
    
    namespace ...;
    
    use Doctrine\ORM\Mapping as ORM;
    
    /**
     * FirstChild
     *
     * @ORM\Table()
     * @ORM\Entity
     */
    class Brand extends NameHolder
    {
        // all methods and properties except from the "name"
    }
    

    所以现在你可以这样查询:

    $group = $this->getDoctrine()
        ->getRepository('AudsurShopBundle:NameHolder')
        ->findOneBy(array('name' => $slug))
        ->getProducts();
    

    这将返回一个包含BrandCategory 实体的数组集合。

    但是我不确定NameHolder 课程是否真的有意义。另一种解决方案是在不更改任何实体的情况下对两个实体进行单独查询,但这似乎不是您想要的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-14
      • 2011-04-01
      • 1970-01-01
      • 2020-05-02
      • 1970-01-01
      • 1970-01-01
      • 2013-09-14
      • 1970-01-01
      相关资源
      最近更新 更多