将另一个 table 的列添加到 CGridView

Add column from another table to CGridView

您好,我正在使用 yii crud 并尝试将另一个 table 的列添加到管理视图

这是我的管理视图 CGridView 小部件代码。

<?php $this->widget('zii.widgets.grid.CGridView', array(
    'id'=>'package-days-grid',
    'dataProvider'=>$model->search(),
    'filter'=>$model,
    'columns'=>array(
        'package_days_id',
        'package_days_description',    
                array(
                    'header' => 'Package Title',
                    'name' => 'package_days_package_id',
                    'value' => function ($data){
                        echo $data->packagePackagedays->package_title;
                    }
                ),
        array(
            'class'=>'CButtonColumn',
        ),
    ),
)); ?>

这是 'PackageDays' 模型中的关系函数。

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(
                    'packagePackagedays' => array(self::BELONGS_TO, 'Packages', 'package_days_package_id'),
        );
    }

这是 'PackageDays' 模型中的搜索功能。

public function search()
    {
        // @todo Please modify the following code to remove attributes that should not be searched.

        $criteria=new CDbCriteria;
                $criteria->with = "packagePackagedays";
        $criteria->compare('package_days_id',$this->package_days_id);
        $criteria->compare('packagePackagedays.package_title',$this->package_days_package_id);
        $criteria->compare('package_days_description',$this->package_days_description,true);

        return new CActiveDataProvider($this, array(
            'criteria'=>$criteria,
        ));
    }

I added the column successfully but I can't search values of newly added column.

如果有人能看一下就好了

确保将 package_days_package_id 添加为包模型的 public 属性。否则 $this->package_days_package_id 不存在

class Packages extends CActiveRecord{

public $package_days_package_id;

...

另外请确保您在“搜索”场景(也在您的包模型中)的“安全”验证规则中添加了 package_days_package_id。否则,您在文本框中键入的值将不会分配给您的 $this->package_days_package_id

public function rules(){

return array(

...

// The following rule is used by search()

array('bunch, of, stuff, ..., package_days_package_id', 'safe', 'on'=>'search'),

如果您还希望网格列在单击时可排序,您还必须创建一个自定义 CSort 并将其提供给您的 CActiveDataProvider