yii使用模型之间的关系获取数据

时间:2013-09-19 15:26:39

标签: php sql yii mysqli

我想获得所有类别和子类别列表enabled=1

类别关系:

return array(
            'subcategories'=>array(self::HAS_MANY, 'Subcategories', 'id','condition'=>'enabled=1'),
        );

子类别中的关系:

return array(
            'categories'=>array(self::BELONGS_TO, 'Categories', 'category_id', 'condition'=>'enabled=1'),
        );

以下是我想做的事情:

$categories = Categories::model()->with('subcategories')->findAll();
    $selectData = array();
    foreach ($categories as $category) {
        $selectData[$category->title] = CHtml::listData($category->subcategories, 'id', 'title');
    }
    echo CHtml::dropDownList('catAndSubcat', null, $selectData);

两个表都有列enabled。每个类别都有近10个子类别。 子类别中的category_id是类别中id的外键

但我得到错误:

 SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'enabled' in where clause is ambiguous. The SQL statement executed was: SELECT `t`.`id` AS `t0_c0`, `t`.`title` AS `t0_c1`, `t`.`page_id` AS `t0_c2`, `t`.`position` AS `t0_c3`, `t`.`enabled` AS `t0_c4`, `subcategories`.`id` AS `t1_c0`, `subcategories`.`category_id` AS `t1_c1`, `subcategories`.`title` AS `t1_c2`, `subcategories`.`page_id` AS `t1_c3`, `subcategories`.`position` AS `t1_c4`, `subcategories`.`enabled` AS `t1_c5` FROM `t_categories` `t` LEFT OUTER JOIN `t_subcategories` `subcategories` ON (`subcategories`.`id`=`t`.`id`) WHERE (enabled=1) 

帮助我!

2 个答案:

答案 0 :(得分:0)

你必须使用这样的表别名:

 array(
        'subcategories'=>array(self::HAS_MANY, 'Subcategories', 'id','condition'=>'subcategories.enabled=1'),
    );
 array(
        'categories'=>array(self::BELONGS_TO, 'Categories', 'category_id', 'condition'=>'categories.enabled=1'),
    );

<强>更新

$categories = Categories::model()->with('subcategories')->findAll(array('condition' => 't.enabled=1'));

答案 1 :(得分:0)

你可以试试。

return array(
        'subcategories'=>array(self::HAS_MANY, 'Subcategories', 'id','on'=>'subcategories.enabled=1'),
    );

我认为条件不适用于关系。

编辑:或者你可以试试。

return array(
    'subcategories'=>array(self::HAS_MANY, 'Subcategories','id'),
);

在你的控制器中:

Categories::model()->with('subcategories')->findAllByAttributes(array('subcategories.enabled'=>1));