0

目前我们有两张桌子。地点和地址

位置与addresses.location_id 上的地址是一对多的关系。

我们正在尝试在 cgridview 中输出与特定位置相关的所有地址:

管理员.php

<?php $this->widget('zii.widgets.grid.CGridView', array(
    'id'=>'locations-grid',
    'dataProvider'=>$location->search(),
    'filter'=>$location,
    'columns'=>array(
        'id',
        'name',
        array(
            'name' => 'address',
            'value' => 'implode("<br>",CHtml::listData($data->addresses(),"id","address"))',
            'filter' => CHtml::activeTextField($location, 'address'),
            'type' => 'html',
        ),/**/  
        array(
            'class'=>'CButtonColumn',
        ),
    ),
)); ?>

模型(locations.php)

public function search()
    {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.
        $criteria=new CDbCriteria;
        $criteria->together = true;
        $criteria->with = array('addresses');
        $criteria->compare('id',$this->id);
        $criteria->compare('name',$this->name,true);
        $criteria->compare('addresses.address',$this->address,true);

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

有没有更好的方法来获取地址数据而不是破坏 $data->addresses 函数?

4

1 回答 1

0

您可以在Locations模型中添加 getter 方法。

public function getAddressNames($separator='<br>')
{
    $names = array();
    foreach($this->adresses as $address) {
        $names[] = $address->address;
    }
    return implode($separator, $names);
}

然后你可以addressNames在你的gridview中使用像一个常规属性。

于 2013-05-24T06:48:34.967 回答