duanjiu2701 2015-01-15 06:21
浏览 41
已采纳

Yii Scope不返回所需的列

In my Ads model, i have a scope, that creates a join to another table

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')        
        );
    }

then in my $dataprovider

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

the scope generates the correct query

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

but in my view i can only get ALL columns in the t.* table. i get a not defined error when trying to calling objects in the t2 table.

What am i doing wrong here? Any ideas?

UPDATE: in my view:

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

code above, gives me this array. It returns 24 array locations, but i only included 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条回答 默认 最新

  • dongshi9719 2015-01-15 08:18
    关注

    This is because the columns of t2 table are not an attributes of Ads model. To overcome that you have to simply add a property of ads model.

    In your case your query should be

    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 .
    

    And add property to your ads model

    public $t2_make;
    

    Then you can access it at your view like $model->t2_make; and $data->t2_make at your gridview.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?