0

我正在尝试使用范围按类别过滤产品,我通过内部加入类别来做到这一点,问题是它只有在我一起打开时才有效,这会打乱分页

我记得这样做没有问题还尝试在 with() 定义中使用 'on'=> 而不是 'condition'=> ,工作原理几乎相同,但我认为后者在 db-wise 方面较慢

有任何想法吗?

附言。不幸的是,离开一个类别的产品不是一种选择

<?php

/**
 * ProductCategory model
 */
class ProductCategory extends CActiveRecord
{
    //...
    public function relations()
    {
        return array(
            //...
            'parent' => array(self::BELONGS_TO, 'ProductCategory', 'parentId'),
            'children' => array(self::HAS_MANY, 'ProductCategory', 'parentId'),
            //...
        );
    }
    //...
}

/**
 * Product model
 */
class Product extends CActiveRecord
{
    //...
    public function relations()
    {
        return array(
            //...
            'categoriesJunction' => array(self::HAS_MANY, 'ProductCategoriesProducts', 'productId'),
            'categories' => array(self::HAS_MANY, 'ProductCategory', array('categoryId'=>'id'), 'through'=>'categoriesJunction'),
            //...
        );
    }

    /**
     * Category scope
     * 
     * @param mixed Category ids the product must belong to (int or array of int)
     * @return \Product
     */
    public function category($category = null) {
        if ($category) {
            $category = ProductCategory::model()->resetScope()->with('children')->findByPk($category);

            if ($category) {
                $categories = array($category->id);

                if (is_array($category->children)) {
                    foreach ($category->children as $child) {
                        $categories[] = $child->id;
                    }
                }

                $this->getDbCriteria()->mergeWith(array(
                    'with' => array(
                        'categories' => array(
                            'on'=>'categories.id=' . implode(' or categories.id=', $categories),
                            'joinType' => 'inner join',
                            //'together'=>true,
                        ),
                    ),
                ));
            }
        }

        return $this;
    }
    //...
}
4

1 回答 1

0

更新:选择 => false 是要走的路

D.Mill 4 月 5 日 9:33

我同意 aboce 的评论,这怎么搞乱分页?也许您正在寻找 'select'=>false (在您的条件数组的 'categories' 部分内)

毕竟我找到了一个适用于范围的非常简单的解决方案,只需将范围标准部分更改为

$this->getDbCriteria()->mergeWith(array(
    'with'=>array(
        'categories'=>array(
            'select'=>'false',
            'on'=>'categories.id=' . implode(' or categories.id=', $categories),
            'joinType'=>'inner join',
        ),
    ),
    'together'=>true,
));
于 2013-04-05T12:40:39.963 回答