使用MySQL的学说,我可以选择父类和子类中的所有产品吗?

时间:2013-11-26 01:11:16

标签: mysql doctrine-orm doctrine dql

我已经做了一些寻找答案,但大多数结果要么不够清楚,要么我觉得很难在我目前的模式中实现......我希望实现的是查询选择所有产品从与类别表中的类别ID匹配的products表中,但是现在我还希望获得作为所述父类别的子类别的产品。我正在使用带有codeigniter的Doctrine 2,到目前为止我的功能看起来像这样

function searchForProducts( $offset, $limit ) {
    $search = $this->input->get('search');
    $category = (int)$this->input->get('category');
    $supplier = (int)$this->input->get('supplier');

    for( $i = 0; $i < 2; $i++ ) {
        $select = ($i == 0) ? 'count(p)' : 'p';
        $qb = $this->em->createQueryBuilder();
        $qb ->select($select)
            ->from(self::ENTITY, 'p');

        if( $i != 0) {
            $qb ->setFirstResult( (int)$offset )
                ->setMaxResults( (int)$limit );
        }

        if( $search ) {
            $qb ->where( "p.title LIKE :search" )
                ->orWhere( "p.sku LIKE :search" )
                ->setParameter('search', "%$search%");
        }

        if( $category ) {
            $qb ->andWhere( "p.category = ?1" )
                ->setParameter(1, $category);
        }

        if( $supplier ) {
            $qb ->andWhere( "p.supplier = ?2" )
                ->setParameter(2, $supplier);
        }

        if( $i == 0 ) {
            $this->totalRows =  $qb->getQuery()->getSingleScalarResult();
        } else {
            return $qb->getQuery()->getResult();
        }
    }   
}

我也不认为从应用程序级别获取所有产品是不切实际的,因为我使用的是分页,产品可能变得非常大。

2 个答案:

答案 0 :(得分:0)

执行Product -> Category -> Child Categories -> Product后,生成的Product将不会在同一列中返回。因此,学说将在同一庄园中保湿。如果你想在所有产品上使用分页,这是不好的。]

最好的办法是使用带有结果集映射的本机SQL。然后,您的查询应使用UNION,以便主Product与子Product的列在同一列中排列

答案 1 :(得分:0)

为了回答我自己的问题,我决定采取简单的方法,并考虑到我最多只有大约40个类别,我不认为这应该是一个很大的问题。

在我的类别模型类中,我创建了2个静态方法

static function getCategoryWithChildren( $id = NULL ) {
    $obj = new self;
    $parent = $obj->getCategory( $id );
    $list = array();
    self::iterateCategoriesChildren($parent, $list);
    return array_reverse($list);    
}

static function iterateCategoriesChildren( $category, &$array ) {
    if( $category->hasChildren() ) {
        foreach( $category->getChildren() as $child ) {
            self::iterateCategoriesChildren($child, $array);                
        }
    }
    $array[] = $category;
}

因此,这将获得父项并迭代所有子项并将每个1分配给平面数组。

然后从我的searchProducts方法中,我在$ category check下添加了一些。

        if( $category ) {
            if( $this->settings->get('product_child_categories') ) {
                $categories = Categories_model::getCategoryWithChildren($category);
                foreach($categories as $_category) {
                    $qb ->orWhere( "p.category = " . $_category->getID() );
                }                   
            } else {                
                $qb ->andWhere( "p.category = ?1" )
                    ->setParameter(1, $category);
            }               
        }

可能不是最好的或实际的,但它可以正常工作并且做我现在需要的。