在我们的网上商店里,我们销售工业计算机系统的备件。因此,我们有两大类:备件和计算机系统。用户可以通过备件类别或通过计算机系统搜索所需的备件。如果用户在主页上选择了他的计算机系统,他应该得到一个与他的计算机系统相匹配的备件类别列表。
因此,我需要查询所有的备件类别,并过滤他们的所有文章,这也是在类别的预选计算机系统。否则,用户可能会看到一个空类别。
我有两种学说:文章和分类--每一种都与许多人有关:
类别实体
/**
* @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;我试图用两个类别中的文章来查询所有类别。例如:获取所有类别,其中有文章在“此”类别,但只有在相同的文章也在“那个”类别。
不幸的是我不知道该怎么做。有人能帮我吗?
发布于 2018-06-21 09:08:19
多亏了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相关联的备件。
发布于 2018-06-20 19:51:46
若要查找属于给定项目列表的类别(每个类别必须与给定列表中的每一篇文章有关联),则可以使用某些聚合。
$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(); https://stackoverflow.com/questions/50948433
复制相似问题