YII框架学习(二)

YII框架的增删改查

例:一个新闻表的增删改查:

(1)首先使用gii工具生成控制器和模型

(2)控制器

<?php

class NewsController extends Controller
{
    public $layout  = false;
    
    //查询
    public function actionIndex()
    {
          
        //获取根目录
        //echo Yii::app()->baseUrl ;die;
        //获取当前控制器路径
        //echo Yii::app()->request->url;die;
        //方式一:
        //多个条件查要用and连接
        //$n=News::model()->find("title=:title and slug=:slug",array(":title"=>'234',":slug"=>'234'));
        //var_dump($n->text);die;
        //方式二:
        $criteria = new CDbCriteria();
        $criteria->order = 'id desc';
        //计算总数
        $count = News::model()->count($criteria);
        $pager = new CPagination($count);
        //设置页大小
        $pager->pageSize = 4;
        $pager->applyLimit($criteria);
        $news = News::model()->findAll($criteria);
        //获取当前页
        $num = Yii::app()->request->getParam('page')?Yii::app()->request->getParam('page'):1;
        $data['news'] = $news;
        $data['pages'] = $pager;
        //分配当前页起始编号
        $data['num'] = ($num-1)*$pager->pageSize;
        //将变量分配到模板
        $this->render('index',$data);
    }
    
    //新增数据
    public function actionAdd(){
        //新增时要new
        $newsModel = new News();
        //设置初始值,避免报错
        $info->id = '';
        $info->title = '';
        $info->text = '';
        if(!empty($_POST)){
            $newsModel->title = $_POST['title'];
            $newsModel->text = $_POST['text'];
            $newsModel->slug = 'aa';
            //判断更新还是新增
            if(!empty($_POST['id'])){
                //更新
                $res = News::model()->updateByPk($_POST['id'], array('title'=>$_POST['title'],'text'=>$_POST['text']));
                if($res){
                    $this->redirect(array('index'));
                }else{
                    $info = News::model()->findByPk($_POST['id']);
                    $data['info'] = $info;
                }
            }else{
                //新增
                //             $res = News::model()->newsAdd($_POST['title'],$_POST['text'], '123test');
                if($newsModel->save()){
                    $this->redirect(array('index'));
                }
            }
            
        }else{
            //获取GET/POST传过来的参数
            $id = Yii::app()->request->getParam('id');
            if(!empty($id)){
                $info = News::model()->findByPk($id);
                $data['info'] = $info;
            }
        }
        $this->render('add', $data);
    }
    
    //删除
    public function actionDel(){
        $id = Yii::app()->request->getParam('id');
        $res= News::model()->findByPk($id)->delete(); // 假设有一个帖子,其 ID 为 10
        $this->redirect(array('index'));
    }

(3)模型(gii生成的)

<?php

/**
 * This is the model class for table "news".
 *
 * The followings are the available columns in table 'news':
 * @property integer $id
 * @property string $title
 * @property string $slug
 * @property string $text
 */
class News extends CActiveRecord
{
    public $attributes;
    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return News the static model class
     */
    public static function model($className=__CLASS__)
    {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return 'news';
    }

    
    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('title, slug, text', 'required'),
            array('title, slug', 'length', 'max'=>128),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('id, title, slug, text', 'safe', 'on'=>'search'),
        );
    }

    /**
     * @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(
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'id' => 'ID',
            'title' => 'Title',
            'slug' => 'Slug',
            'text' => 'Text',
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search()
    {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria=new CDbCriteria;

        $criteria->compare('id',$this->id);
        $criteria->compare('title',$this->title,true);
        $criteria->compare('slug',$this->slug,true);
        $criteria->compare('text',$this->text,true);

        return new CActiveDataProvider($this, array(
            'criteria'=>$criteria,
        ));
    }
}

(4)视图:

index.php

<table>
<tr>
    <th>编号</th>
    <th>标题</th>
    <th>内容</th>
    <th>操作</th>
</tr>
<?php 
    $i = $num;
    foreach($news as $val){
        $i++;
?>
<tr>
    <td><?= $i?></td>
    <td><?= $val->title?></td>
    <td><?=  $val->text?></td>
    <td><a href="<?= $this->createUrl('add', array('id' => $val->id))?>">编辑</a> <a href="<?= $this->createUrl('del',array('id'=>$val->id))?>">删除</a></td>
</tr>
<?php
    }
?>
<tr><td colspan="4">
<?php 
$this->widget('CLinkPager',array(    
        'header'=>'',    
        'firstPageLabel' => '首页',    
        'lastPageLabel' => '末页',    
        'prevPageLabel' => '上一页',    
        'nextPageLabel' => '下一页',    
        'pages' => $pages,    
        'maxButtonCount'=>13    
        )    
    );   
?>
</td></tr>
</table>

add.php

<h3>添加</h3>
<form method="post"  action="">
    标题:<input type="text" name="title" value="<?= $info->title?>"><br>
    内容:<textarea rows="5" cols="10" name="text"><?= $info->text ?></textarea><br>
    <input type="submit" name="sub" value="提交">
    <input type="hidden" name="id" value="<?= $info->id?>">
</form>
时不我待,不负韶华!立刻行动!不吃学习的苦就会吃生活的苦!
原文地址:https://www.cnblogs.com/zrp2013/p/3651685.html