我通过CDbCriteria加入了模型中的一些表,我的代码是这样的:

$crt = new CDbCriteria();
        $crt->alias = 'so';
        $crt->select = 'u.id, u.first_name, u.last_name';
        $crt->join = " inner join " . Flow::model()->tableName() . " as fl on fl.id = so.flow_id";
        $crt->join .= " inner join " . RoleUser::model()->tableName() . " as ru on ru.id = fl.receiver_role_user_id";
        $crt->join .= " inner join " . User::model()->tableName() . " as u on ru.user_id= u.id";
        $crt->compare('sms_outbox_group_id', $smsOutboxGroupId);
        $crt->compare('fl.kind', Flow::KIND_SMS);
        $crt->group = 'u.id';

        $smsOutBox = new SmsOutbox();
        return new CActiveDataProvider($smsOutBox, array(
            'criteria' => $crt,
            'sort' => array(
                'defaultOrder' => 'so.id DESC',
            )
        ));

如何在CGridView中显示所选的列?有没有可能在不定义模型关系的情况下显示first_namelast_name的方法?

最佳答案

我已经使用Sudhanshu Saxena答案找到了解决方案。除了为first_namelast_name使用别名之外,我还添加了两个与别名同名的属性:receiverFirstNamereceiverLastName。这样,我的问题得以解决,此外它还提供了这两个属性的搜索功能。
我的最终代码是这样的:

Model :
public $receiverFirstName;
public $receiverLastName;

创建条件:
$crt = new CDbCriteria();
        $crt->alias = 'so';
        $crt->select = 'so.id,u.id as userId, u.first_name as receiverFirstName, u.last_name as receiverLastName, so.status';
        $crt->join = " inner join " . Flow::model()->tableName() . " as fl on fl.id = so.flow_id";
        $crt->join .= " inner join " . RoleUser::model()->tableName() . " as ru on ru.id = fl.receiver_role_user_id";
        $crt->join .= " inner join " . User::model()->tableName() . " as u on ru.user_id= u.id";
        $crt->compare('sms_outbox_group_id', $smsOutboxGroupId);
        $crt->compare('u.first_name', $this->receiverFirstName, true);
        $crt->compare('u.last_name', $this->receiverLastName, true);
        $crt->compare('so.status', $this->status);
        $crt->compare('fl.kind', Flow::KIND_SMS);
        $crt->group = 'userId';
        $crt->order = 'so.id';


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

最后在CgridView中,我做到了:
'columns' => array(
    array(
        'header' => Yii::t('app', 'Row'),
        'value' => '$this->grid->dataProvider->pagination->currentPage * $this->grid->dataProvider->pagination->pageSize + ($row+1)',
    ),
    array(
        'name' => 'receiverFirstName',
        'value' => '$data->receiverFirstName',
    ),
    array(
        'name' => 'receiverLastName',
        'value' => '$data->receiverLastName',
    ),
    array(
        'name' => 'status',
        'value' => 'SmsOutbox::getStatusTitle($data->status)',
        'filter' => CHtml::listData(SmsOutbox::getStatusList(), 'id', 'title')
    ),

),

关于php - 在CGridView中显示联接表中的列,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17022501/

10-13 09:30