CGridView查询中遇到的问题,unsetAttributes() 方法

控制器代码:

public function actionIndex()
{
	$model=new Staff('search');
	if(isset($_GET['Manager']))
		$model->attributes=$_GET['Manager'];

	$this->render('index',array(
		'model'=>$model,
	));
}
将model传到CGridView,数据库有一条记录,但是却不显示。

CGridView代码部分如下:

<?php $this->widget('zii.widgets.grid.CGridView', array(
	'ajaxUpdate' => false,
	'id'=>'staff-grid',
	'itemsCssClass' => 'data_list',
	'dataProvider'=>$model->search(),
	'template' => '{items}{pager}',
	'pager' => array(
		'class'=>'LLinkPager',
	),
	'pagerCssClass' => 'myPager',
	'enableSorting' => false,
	'emptyText'=>'暂无数据',
	'columns'=>array(
		...
	),
));
?>
对比默认生成的代码发现,在$model=new Staff('search');代码下有一行代码:$model->unsetAttributes(); 加上该代码后,发现数据可以显示。Why?

查看一下unsetAttributes() 方法

unsetAttributes() 方法(可用自 v1.1.3)
public void unsetAttributes(array $names=NULL)
$names array list of attributes to be set null.
If this parameter is not given, all attributes
as specified by attributeNames will have their values unset.

源码: framework/base/CModel.php#482 (隐藏)
public function unsetAttributes($names=null)
{
    if($names===null)
        $names=$this->attributeNames();
    foreach($names as $name)
        $this->$name=null;
}
该方法目的是将属性设置为NULL。

测试:

public function actionIndex()
{
	$model=new Staff('search');
	var_dump($model->attributes);
	exit;
	$model->unsetAttributes();
	if(isset($_GET['Manager']))
		$model->attributes=$_GET['Manager'];

	$this->render('index',array(
		'model'=>$model,
	));
}
结果为:

array(6) {
  ["sector_id"]=>
  string(1) "0"
  ["password"]=>
  string(0) ""
  ["permission"]=>
  int(0)
  ["logintime"]=>
  int(0)
  ["id"]=>
  NULL
  ["username"]=>
  NULL
}
怎么sector_id值为0?原来,我在数据库中将sector_id的默认值设为0,是不是问题在这?于是,我将该字段默认值设置为2,刷新

结果为:

array(6) {
  ["sector_id"]=>
  string(1) "2"
  ["password"]=>
  string(0) ""
  ["permission"]=>
  int(0)
  ["logintime"]=>
  int(0)
  ["id"]=>
  NULL
  ["username"]=>
  NULL
}
原来如此。

因为数据库中的一条记录,它的sector_id的值为1,你以0查询,当然是找不到数据喽。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值