Yii 范围不返回所需的列


Yii Scope not returning desired columns

在我的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] => )

这是因为 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在网格视图中访问它。