dongtaigan1594 2013-05-23 09:33
浏览 37
已采纳

与HasMany的Yii Relation数据问题

Currently we have two tables. Locations and Addresses

Locations are a 1 to many relation to addresses on addresses.location_id.

We are trying to output all addresses related to a specific location in the cgridview:

admin.php

  1. <?php $this->widget('zii.widgets.grid.CGridView', array(
  2. 'id'=>'locations-grid',
  3. 'dataProvider'=>$location->search(),
  4. 'filter'=>$location,
  5. 'columns'=>array(
  6. 'id',
  7. 'name',
  8. array(
  9. 'name' => 'address',
  10. 'value' => 'implode("<br>",CHtml::listData($data->addresses(),"id","address"))',
  11. 'filter' => CHtml::activeTextField($location, 'address'),
  12. 'type' => 'html',
  13. ),/**/
  14. array(
  15. 'class'=>'CButtonColumn',
  16. ),
  17. ),
  18. )); ?>

model (locations.php)

  1. public function search()
  2. {
  3. // Warning: Please modify the following code to remove attributes that
  4. // should not be searched.
  5. $criteria=new CDbCriteria;
  6. $criteria->together = true;
  7. $criteria->with = array('addresses');
  8. $criteria->compare('id',$this->id);
  9. $criteria->compare('name',$this->name,true);
  10. $criteria->compare('addresses.address',$this->address,true);
  11. return new CActiveDataProvider($this, array(
  12. 'criteria'=>$criteria,
  13. ));
  14. }

Is there a better way of going about getting the address data rather then imploding the $data->addresses function?

展开全部

  • 写回答

1条回答 默认 最新

  • dousi4900 2013-05-23 22:48
    关注

    You can add a getter method to your Locations model.

    1. public function getAddressNames($separator='<br>')
    2. {
    3. $names = array();
    4. foreach($this->adresses as $address) {
    5. $names[] = $address->address;
    6. }
    7. return implode($separator, $names);
    8. }

    Then you can use addressNames like a regular attribute in your gridview.

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

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部