17.Yii2.0框架模型添加记录

[TOC]

新建控制器 HomeController.php

D:\xampp\htdocs\yii\controllers\HomeController.php

<?php
/**
 * Created by Haima.
 * Author:Haima
 * QQ:228654416
 * Date: 2018/9/4
 * Time: 06:30
 */

namespace app\controllers;

use app\models\Article;
use yii\web\Controller;

header("Content-Type: text/html;charset=utf-8");
class HomeController extends Controller
{
    //用属性的方法定义父模板
    //会自动加载D:\phpStudy\WWW\yii\views\layouts\home.php文件
    public $layout = 'home';
    public function actionIndex()
    {
        
        $article = new Article;
        $article->article_title = '知微又涨粉啦!《天盛长歌》小衣衣、楚王和金狮王子你会选谁?';
        $article->num = 18;
        // $data = $article->insert(); //保存方法一
        $data = $article->save(); //保存方法二
        $id = $article->attributes['article_id']; //获取新插入的主键id

        dd($id);
        die;
        //会自动加载父模板 D:\phpStudy\WWW\yii\views\layouts\home.php
        return $this->render('index');
    }
  
}

新建model Article.php

D:\xampp\htdocs\yii\models\Article.php

<?php
namespace app\models;

use yii\db\ActiveRecord;

class Article extends ActiveRecord
{

}

posted @ 2018-09-04 07:34  HaimaBlog  阅读(400)  评论(0编辑  收藏  举报