Yii Scope不返回所需的列

时间:2015-01-15 06:21:44

标签: php yii

在我的Ads模型中,我有一个范围,它创建了另一个表的连接

public function scopes()
    {
        return array(
            'GetCustom'=> array(
                    'alias' => 't',
                    'select'=> 't.*, t2.make, COUNT(t2.id) AS Count',
                    'join' => 'JOIN `make` AS t2',
                    'condition'=>'t.make_id=t2.id AND t.pending!=1',
                    'group'=>'t2.make',
                    'order'=>'Count DESC',
                    'limit'=>'24'

            ),
        );
    }

public function relations()
    {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
            '_make' => array(self::BELONGS_TO,'Make', 'make_id')        
        );
    }

然后在我的$dataprovider

$dataProvider=new CActiveDataProvider(Ads::model()->GetCustom(), array(
                        'pagination'=>false, //disable pagination
                    ));

范围生成正确的查询

SELECT t.*,t2.make, COUNT(t2.id) AS Count FROM `ads`
`t` JOIN `make` AS t2 WHERE t.make_id=t2.id AND t.pending!=1 GROUP
BY t2.make ORDER BY Count DESC LIMIT 24

但在我的view我只能获得t.*表中的所有列。尝试调用t2表中的对象时,我得到一个未定义的错误。

我在这里做错了什么?有什么想法吗?

更新 在我看来:

 $a = Ads::model()->GetCustom()->findAll();
    print_r($a);
上面的

代码,给了我这个数组。它返回24个数组位置,但我只包含1个。

Array ( [0] => Ads Object ( [state_name] => [contact_method] => [file] => [mime_type] => [size] => [name] => [filename] => [secureFileNames] => [_new:CActiveRecord:private] => [_attributes:CActiveRecord:private] => Array ( **[ALL COLUMNS IN TABLE ADS ONLY!!!]** ) [_related:CActiveRecord:private] => Array ( ) [_c:CActiveRecord:private] => [_pk:CActiveRecord:private] => 1 [_alias:CActiveRecord:private] => t [_errors:CModel:private] => Array ( ) [_validators:CModel:private] => [_scenario:CModel:private] => update [_e:CComponent:private] => [_m:CComponent:private] => )

1 个答案:

答案 0 :(得分:0)

这是因为t2表的列不是广告模型的属性。 要克服这一点,您只需添加广告模型的属性。

在您的情况下,您的查询应该是

SELECT t.*,**t2.make as t2_make**, COUNT(t2.id) AS Count FROM `ads`
`t` JOIN `make` AS t2 WHERE t.make_id=t2.id AND t.pending!=1 GROUP
BY t2.make ORDER BY Count DESC LIMIT 24 .

并为广告模型添加属性

public $t2_make;

然后,您可以在网格视图中的$model->t2_make;$data->t2_make视图中访问它。