在 Yii 自动生成的代码里,我们总能在 admin 的界面看到 CGridView 的身影。这是一个很好用的展示数据的表格控件,用的好可以明显地加快开发进度。下面就让我们来探索一下 CGridView 的基本使用吧:
简单起见,我们的代码就用 Yii demo 中的 blog 例子来做修改。首先,这是修改后的部分 Mysql 语句:
drop table if exists `tbl_user`;
CREATE TABLE tbl_user
(
`user_id` INTEGER NOT NULL AUTO_INCREMENT comment '主键',
`username` VARCHAR(128) NOT NULL comment '用户名',
`nickname` VARCHAR(128) NOT NULL comment '昵称',
`password` VARCHAR(128) NOT NULL comment '密码',
`email` VARCHAR(128) NOT NULL comment '邮箱',
`is_delete` tinyint not null default 0 comment '删除标志',
unique key(`username`),
primary key (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 comment='用户表';
drop table if exists `tbl_post`;
CREATE TABLE tbl_post
(
`post_id` INTEGER NOT NULL AUTO_INCREMENT comment '主键',
`title` VARCHAR(128) NOT NULL comment '标题',
`content` TEXT NOT NULL comment '文章内容',
`tags` TEXT comment '标签',
`status` INTEGER NOT NULL comment '状态,0 = 草稿,1 = 审核通过,-1 = 审核不通过,2 = 发布',
`create_time` INTEGER comment '创建时间',
`update_time` INTEGER comment '更新时间',
`author_id` INTEGER NOT NULL comment '作者',
`is_delete` tinyint not null default 0 comment '删除标志',
CONSTRAINT `post_ibfk_1` FOREIGN KEY (author_id)
REFERENCES tbl_user (`user_id`) ON DELETE CASCADE ON UPDATE RESTRICT,
primary key (`post_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 comment='日志表';
两个表一个存储作者信息一个存储日志,其中日志有一个外键关联到 user。两个表里面的 is_delete 字段是标志该条记录是否被删除,0 为未删除,1 为已删除。让我们看一下用 gii 生成的 Post 类的 relation 方法:
/**
* @return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'comments' => array(self::HAS_MANY, 'Comment', 'post_id'),
'author' => array(self::BELONGS_TO, 'User', 'author_id'),
);
}
其中的 author 外键作为 BELONGS_TO 关系存在,符合我们的预期。
说了这么多,看看自动生成的 Post 中 admin.php 里 CGridView 的代码吧:
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'post-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
'post_id',
'title',
'content',
'tags',
'status',
'create_time',
'update_time',
'author_id',
'is_delete',
array(
'class'=>'CButtonColumn',
),
),
)); ?>