在 Yii 自動(dòng)生成的代碼里,我們總能在 admin 的界面看到 CGridView 的身影。這是一個(gè)很好用的展示數(shù)據(jù)的表格控件,用的好可以明顯地加快開(kāi)發(fā)進(jìn)度。下面就讓我們來(lái)探索一下 CGridView 的基本使用吧:
簡(jiǎn)單起見(jiàn),我們的代碼就用 Yii demo 中的 blog 例子來(lái)做修改。首先,這是修改后的部分 Mysql 語(yǔ)句:
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 '刪除標(biāo)志', 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 '標(biāo)題', `content` TEXT NOT NULL comment '文章內(nèi)容', `tags` TEXT comment '標(biāo)簽', `status` INTEGER NOT NULL comment '狀態(tài),0 = 草稿,1 = 審核通過(guò),-1 = 審核不通過(guò),2 = 發(fā)布', `create_time` INTEGER comment '創(chuàng)建時(shí)間', `update_time` INTEGER comment '更新時(shí)間', `author_id` INTEGER NOT NULL comment '作者', `is_delete` tinyint not null default 0 comment '刪除標(biāo)志', 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='日志表';
兩個(gè)表一個(gè)存儲(chǔ)作者信息一個(gè)存儲(chǔ)日志,其中日志有一個(gè)外鍵關(guān)聯(lián)到 user。兩個(gè)表里面的 is_delete 字段是標(biāo)志該條記錄是否被刪除,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 關(guān)系存在,符合我們的預(yù)期。
    說(shuō)了這么多,看看自動(dòng)生成的 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',     ),   ), )); ?>             
新聞熱點(diǎn)
疑難解答