与HasMany的Yii Relation数据问题

时间:2013-05-23 17:33:20

标签: php yii

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

位置与addresses.location_id上的地址有1对多的关系。

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

admin.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',
        ),
    ),
)); ?>

model(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-&gt;地址函数?

1 个答案:

答案 0 :(得分:0)

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

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

然后,您可以像使用gridview中的常规属性一样使用addressNames