alan51 2016-04-28 14:17:12 18623次浏览 1条评论 10 2 0

个人博文

请访问:诗意的边缘

或者直接访问 http://www.alan51.com

例子用于记录自己学习yii2的一些记录

控制器代码

[代码]

<?php
namespace app\modules\manage\controllers\api;
use app\modules\manage\models\Course;
use yii;

class CourseController extends BaseController
{
    /**
     * 课程列表
     *
     * @author Alan51
     * @access public
     * @since 1.0
     * @return array
     */
    public function actionItems()
    {
        $nickname = Yii::$app->request->get('name', '');
        $model = new Course();
        $page = Yii::$app->request->get('page', '');
        $data = $model->itemsCourse($nickname, $page);
        return $this->prompt(200, '成功', $data);
    }

    /**
     * 编辑课程
     * @author Alan51
     * @access public
     * @since 1.0
     * @return array
     */
    public function actionEdit()
    {
        $model = Course::find()->andWhere(['id'=>Yii::$app->request->post('id')])->one();
        $model->setScenario('update');
        if($model->load(Yii::$app->request->post(), '') && $model->validate()) {
            $result = $model->save(false);
            if($result) {
                return $this->prompt(200, '成功', $result);
            }
        }
        $model_error = $model->getFirstErrors();
        if($model_error) {
            $error = implode(' ', $model_error);
        } else {
            $error = '失败';
        }
        return $this->prompt(400, $error, $model_error);
    }

    /**
     * 创建课程
     * @author Alan51
     * @access public
     * @since 1.0
     * @return array
     */
    public function actionAdd()
    {
        $teacher_model = new Course();
        $teacher_model->setScenario('create');
        if($teacher_model->load(Yii::$app->request->post(), '') && $teacher_model->validate()) {
            $result = $teacher_model->save(false);
            if($result) {
                return $this->prompt(200, '成功', $result);
            }
        }
        $error = $teacher_model->ReturnError();
        return $this->prompt(400, $error['error_msg'], $error['error_arr']);
    }

    public function actionDelete()
    {
        $model = Course::find()->andWhere(['id'=>Yii::$app->request->post('id', '')])->one();
        if($model) {
            $ret = $model->delete();
            if($ret) {
                return $this->prompt(200, '成功', $ret);
            }
        }
        return $this->prompt(400, '失败');
    }

}

模型

[代码]

<?php
/**
 * 文件名称: Course.php.
 * 作者名称: Alan51
 * 创建时间: 2016/4/22 13:57
 */

namespace app\modules\manage\models;


use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;

class Course extends ActiveRecord
{
    public static function tableName()
    {
        return 'curriculum';
    }
    public function rules()
    {
        return [
            [['teacher_id', 'name', 'price', 'address', 'class_time', 'limit_num', 'description'], 'required', 'message'=>"请输入{attribute}", 'on'=>['create', 'update']],
            [['limit_num', 'teacher_id'], 'number', 'message'=>'请填入正确的{attribute}', 'on'=>['create', 'update']],
            ['class_time', 'compare_time',  'message'=>'{attribute}不能小于当前时间', 'on'=>['create', 'update']],
            ['limit_num', 'compare', 'compareValue'=>$this->use_num, 'operator'=>'>', 'message'=>'{attribute}不能大于已招人数,已招人数为:'.$this->use_num, 'on'=>'update'],
            ['description', 'safe']
        ];
    }
    public function compare_time($label) {
        $time = $this->class_time;
        if(is_int($time)) {
            if($time < time()) {
                $this->addError($label, '选择的时间不能小于当前时间');
            }
        } else {
            $r = strtotime($time);
            if (!$r) {
                $this->addError($label, '请选择正确的时间');
            }
            if (strtotime($time)<time()) {
                $this->addError($label, '选择的时间不能小于当前时间');
            }
        }

    }
    public function scenarios()
    {
        return [
            'create'=>['teacher_id', 'name', 'price', 'address', 'class_time', 'limit_num', 'description', 'create_time', 'update_time'],
            'update'=>['teacher_id', 'name', 'price', 'address', 'class_time', 'limit_num', 'description', 'update_time'],
        ];
    }
    public function behaviors()
    {
        return [
            'timestamp'=>[
                'class'=>TimestampBehavior::className(),
                'attributes'=>[
                    ActiveRecord::EVENT_BEFORE_INSERT => ['create_time', 'update_time'],
                    ActiveRecord::EVENT_BEFORE_UPDATE => ['update_time']
                ]
            ]
        ];
    }
    public function attributeLabels()
    {
        return [
            'teacher_id' => '老师',
            'name' => '课程名',
            'price' => '报名费用',
            'address' => '上课地点',
            'class_time' => '上课时间',
            'limit_num' => '限招人数',
            'description' => '描述'
        ];
    }
    public function afterValidate()
    {
        $this->class_time = strtotime($this->class_time);
    }

    public function ReturnError() {
        $model_error = $this->getFirstErrors();
        if($model_error) {
            $error = implode(' ', $model_error);
        } else {
            $error = '失败';
        }
        return ['error_msg'=>$error, 'error_arr'=>$model_error];
    }

    /**
     * 获取课程
     * @author Alan51
     * @access public
     * @param string $name
     * @param string $page
     * @param int $limit
     * @since 1.0
     * @return array
     */
    public function itemsCourse($name='', $page='', $limit=10) {
        $model = $this->find();
        if($name) {
            $model->andWhere(['like', 'curriculum.name', $name]);
        }
        if(!$page) {
            return $model->orderBy('create_time desc')
                ->all();
        }
        $count = $model->count();
        $page_no = ($page - 1) * $limit;
        $items = $model->orderBy('create_time desc')
            ->limit($limit)
            ->leftJoin('teacher', 'teacher.id=curriculum.teacher_id')
            ->select('curriculum.*,teacher.name as teacher_name')
            ->offset($page_no)
            ->asArray()
            ->all();
        $data['items'] = $items;
        $data['total'] = $count;
        $data['page'] = ceil($count/$limit);
        return $data;
    }

    /**
     * 根据老师删除该老师的课程
     * @author Alan51
     * @access public
     * @param $id
     * @since 1.0
     * @return array
     */
    public function deleteCourseByTeacherId($id)
    {
        return $this->find()->createCommand()->delete($this->tableName(), ['teacher_id'=>$id])->execute();
    }
}

***注意
有些验证类型不支持message,比如:
['mobile', 'string', 'min' => 11,'max' => 11,'tooShort'=>'{attribute}位数为11位','tooLong'=>'{attribute}位数为11位', 'on'=>['create', 'update']],
消息提示在tooShort和tooLong上面
scenarios是场景,在控制器中选择需要setScenarios进行选择,上面代码体现。

更多原文技术性的内容请访问我的博客:诗意的边缘 或者 访问:http://www.alan51.com

觉得很赞
  • 评论于 2019-04-03 11:03 举报

    有个问题想问下楼主 在做场景update 的时候 是需要用findOne 的 但是这个时候validate required 是不生效的 这个时候该怎么办 。难道要手动验证一些必填项吗 required

您需要登录后才可以评论。登录 | 立即注册