您的位置:首页 > 其它

CGridView查询中 unsetAttributes() 方法详解

2016-01-13 00:00 435 查看
控制器代码:



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查询,当然是找不到数据喽。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: