我正在尝试使用范围按类别过滤产品,我通过内部加入类别来做到这一点,问题是它只有在我一起打开时才有效,这会打乱分页
我记得这样做没有问题还尝试在 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;
}
//...
}