YII框架 CGridview显示字段上面加连接LINK

jerry Yii 2015年08月18日 收藏

比如:还是那2张表

  1. url_info ; category
  2. url_info 字段: idcid ,titleurl
  3. category字段:id ,name

其中url_info.cid=category.id
目的:根据category的name 查出URL_INFO中相对应的URL
比如我有一个有 名字叫:魔兽世界 (也就是:category.name=魔兽世界),我想找出和魔兽世界相关系的网站,比如它的官网地址 下载地址等。
YII 框架其实很好了用的。只要你写出2个表的关系:

  1. /**
  2. * @return array relational rules.
  3. */
  4. public function relations()
  5. {
  6. // NOTE: you may need to adjust the relation name and the related
  7. // class name for the relations automatically generated below.
  8. return array(
  9. 'category'=>array(self::BELONGS_TO, 'category', 'cid'),
  10. );
  11. }

显示层:

  1. $this->widget('zii.widgets.grid.CGridView', array(
  2.     'dataProvider'=>$dataProvider,
  3.     'columns'=>array(
  4.         'id',
  5.         array( 'class'=>'CLinkColumn',
  6.                         'header'=>'游戏类别名称',//显示表名称
  7.                         'labelExpression'=>'$data->category_name',//显示名称
  8.                         'urlExpression'=>'Yii::app()->createUrl("url_info",array("cid"=>$data->id))',//显示URL
  9.                         //'linkHtmlOptions'=>array('title'=>'See all entries with this last name')
  10.                         ),
  11.         'category_style',
  12.         'sort_num',
  13.         array(
  14.             'class'=>'CButtonColumn',
  15.         ),
  16.     ),

其中我用到了YII框架中自带的CLinkColumn属性。
还有种办法:

  1. $this->widget('zii.widgets.grid.CGridView', array(
  2.     'dataProvider'=>$dataProvider,
  3.     'columns'=>array(
  4.         'id',
  5.          array(            
  6.             'name'=>'category_name',
  7.             'value'=>'CHtml::link($data->category_name,$url)',//名称和URL
  8.         ),
  9.         'category_style',
  10.         'sort_num',
  11.         array(
  12.             'class'=>'CButtonColumn',
  13.         ),
  14.     ),

这种方法用的是CHtml::link()
然后只要在url_info的控制层中写出

  1. $dataProvider=new CActiveDataProvider('url_info', array(
  2.             'criteria'=>array(
  3.                 'condition'=>'cid=:id',
  4.                 'params'=>array(':cid'=>$_GET['cid']),
  5.                 'with'=>array('category'),
  6.                 'order'=>'cid desc',
  7.             ),
  8.             'pagination'=>array(
  9.                 'pageSize'=>self::PAGE_SIZE,
  10.             ),
  11.         ));

就好了!