主义ORM:按2个类别过滤文章

时间:2018-06-20 12:35:59

标签: php doctrine-orm orm

在我们的在线商店中,我们出售工业计算机系统的备件。因此,我们有2个主要类别:备件和计算机系统。用户可以通过备件类别或计算机系统搜索所需的备件。如果用户在主页上选择了他的计算机系统,则应该获得与他的计算机系统匹配的零件类别列表。

因此,我需要查询所有备件类别并按所有文章过滤它们,这些文章也属于预选计算机系统的类别。否则,用户可能会看到一个空类别。

我有2个学说实体:文章和类别-它们彼此之间有很多很多的关联:

类别实体

/**
 * @ORM\Table(name="categories")
 * @ORM\Entity(repositoryClass="Repository")
 */
class Category extends ModelEntity
{

    /**
     * @var ArrayCollection
     *
     * @ORM\ManyToMany(targetEntity="Models\Article\Article")
     * @ORM\JoinTable(name="articles_categories",
     *      joinColumns={
     *          @ORM\JoinColumn(name="categoryID", referencedColumnName="id")
     *      },
     *      inverseJoinColumns={
     *          @ORM\JoinColumn(name="articleID", referencedColumnName="id")
     *      }
     * )
     */
    private $articles;

文章实体:

/**
 * @ORM\Entity(repositoryClass="Repository")
 * @ORM\Table(name="articles")
 */
class Article extends ModelEntity
{

    /**
     * @var ArrayCollection
     *
     * @ORM\ManyToMany(targetEntity="Models\Category\Category")
     * @ORM\JoinTable(name="articles_categories",
     *      joinColumns={
     *          @ORM\JoinColumn(name="articleID", referencedColumnName="id")
     *      },
     *      inverseJoinColumns={
     *          @ORM\JoinColumn(name="categoryID", referencedColumnName="id")
     *      }
     * )
     */
    protected $categories;

我正在尝试用2个类别的文章查询所有类别。例如:获取所有具有“此”类别中的文章的类别,但仅在“该”类别中具有相同文章的地方。

不幸的是,我不知道如何执行此操作。有人可以帮我吗?

2 个答案:

答案 0 :(得分:1)

要查找属于给定文章列表的类别(每个类别必须与给定列表中的每个文章都有关联),则可以利用某些汇总

$articleIds = [1,2,3,4,5];
$qb = $this->createQueryBuilder('c');
        $qb->addSelect('COUNT(DISTINCT  a.id) AS HIDDEN total_articles')
           ->innerJoin('c.articles', 'a')
           ->add('where', $qb->expr()->in('a', $articleIds))
           ->groupBy('c.id')
           ->having('total_articles = '.count($articleIds))
           ->getQuery()
           ->getResult(); 

答案 1 :(得分:1)

多亏了哈立德·朱奈德(M Khalid Junaid),我终于明白了。 这是我的最终查询:

// select all active root categories from the online shop
$builder = Shopware()->Models()->createQueryBuilder();
$builder->from('Models\Category\Category', 'c')
        ->select('c as category')
        ->andWhere('c.active = 1')
        ->andWhere('c.parentId = 0');

// if the user already selected his computer system,
// only get articles, that are in both categories: the
// category of this particular computer system and the
// category of spare parts
if ($this->computerSystemCategoryId) {

    $builder->addSelect('COUNT(DISTINCT a2.id) AS total_system_articles')
            ->leftJoin('c.articles', 'a2')
            ->leftJoin('a2.categories', 'c2')
            ->groupBy('c.id')
            ->having('total_system_articles > 0')
            ->andWhere($builder->expr()->in('c2', [$this->computerSystemCategoryId]));

}

$query = $builder->getQuery();
$categories = $query->getResult();

通过此查询,我只能获取与特定备件类别关联的备件,而且还与特定计算机系统类别ID关联。