php - 仅选择具有相关模型的模型或具有相关模型的后代模型

标签 php sql activerecord yii

因此,有类别和产品,我需要选择不为空的类别才能构建产品类别菜单。 非空意味着该类别包含产品或后代类别包含产品。我想用瞄准镜来做到这一点,但我似乎无法走得太远。

类似于以下内容,但我需要递归地检查类别层次结构中的更多级别

/**
 * This is the model class for table "shopCategories".
 *
 * The followings are the available columns in table 'shop_categories':
 * @property integer $id
 * @property integer $parentId
 * @property integer $order
 * @property integer $isActive
 * @property integer $cstamp
 * @property integer $mstamp
 *
 * The followings are the available model relations:
 * @property ProductCategory $parent
 * @property ProductCategory[] $children
 * @property ProductCategoryL10n[] $l10n
 * @property ProductCategoriesProducts[] $productsJunction
 */
class ProductCategory extends BogoActiveRecord
{
...

public function nonEmpty()
{    
    $this->getDbCriteria()->mergeWith(array(
        'with' => array(
            'children',
            'children.products'=>array(
                'condition'=>'products.isActive=1',
                'joinType'=>'INNER JOIN', 'limit'=>1
            ),
        ),
    ));

    return $this;
}

...
}

最佳答案

递归是数据库确实不擅长的事情(例如MySql根本不支持递归)。不幸的是,你所要求的东西是不可能直接实现的。

您的选择是:

  1. 在 PHP 中进行过滤。
  2. 修改您的数据库架构以使用 modified preorder tree traversal (MPTT),更新您的模型并再次询问。

关于php - 仅选择具有相关模型的模型或具有相关模型的后代模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10208447/

相关文章:

php - Drupal 在 SQL 中创建时间戳?

sql - 使 SSMS 启动并连接到数据库的 URL?

ruby-on-rails - 按事件记录中的外键排序

sql - PostgreSQL - 将数值从 jsonb 字段复制到整数列

ruby-on-rails-3 - 在 Rails 3 查询中使用 count() 和 group(),还是只使用 sql?

mysql - 为多个查询获取 rails ActiveRecord 而不是对象数组

php - 将 PHP 数组转换为单个变量

php - Symfony 2 - 基于实体关联的动态表单生成

php - SQLite多线程-避免不必要的读者阻塞

sql - 规范化 SQL 数据库