[转]关于Yii中CGridView关联表字段的filter问题解决方法

转载自:http://blog.sina.com.cn/s/blog_497d88270100qi4g.html

当你想用CGridView控件来生成一个Grid表格的时候,是非常方便的,你只需要简单的指定几个属性就可以了,比如:
 $this->widget('zii.widgets.CGridView', array(
  'id'=>'order-grid-view',
  'dataProvider'=>$model->search(),
  'filter'=>$model,
  'columns'=>array(
    'id',
    'customer_cd'
  ),
  )

关于Yii中CGridView关联表字段的filter问题解决方法

 问题是,当你需要多多表进行查询的时候,filter就需要多作一点工作了,很遗憾,我没有找到Yii官方对此问题的简易方法,所以,只能靠迂回的方式了。
首先,让关联表字段显示在Grid表格里面很容易,你可以在dataProvider属性加上关联表,然后columns属性里直接加上要显示的关联表属性就可以,比如,修改后的dataProvider为
'dataProvider'=>$model->with('relationNameToOtherTable')->search(),
修改后的columns属性为:
'columns'=>array(
    'id',
    'customer_cd',
    'customer_nm'=>array(
        'name'=>'relationNameToOtherTable.customer_nm',
    ),
),
但这时的customer_nm是不具备filter域的
解决方法如下:(修改主表对应的Model类)
1)手动为主表增加关联表属性,public $this->customer_nm;
2) 修改search()方法,增加如下两行:$criteria->with = 'relationNameToOtherTable';//relationNameToOtherTable是你在relations里面定义的键值
$criteria->compare('customer_nm', $this->customer_nm);
3)增加afterFind()方法到主表的model类,方法内容如下:$this->customer_nm = $this->relationNameToOtherTable->customer_nm;

这时,你就可以不像前面写的那样修改dataProvider和columns了,因为你手动增加的那个属性已经把关联表的字段属性加进来了,直接用就可以了,最终view代码如下:
'dataProvider'=>$model->search();
'columns'=>array(
    'id',
    'customer_cd',
    'customer_nm'=>array(
        'name'=>'relationNameToOtherTable.customer_nm',
    ),
),

ok, that's all, not the best solution, but it works any way, well if you have some good ideas for this kind of problem feel free to tell me, thanks a lot!!

转载于:https://www.cnblogs.com/DavidYan/articles/2184896.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值