yii---模型的创建

在 model/ 路径新建 Test.php 模型

我们类的名称一定要与数据表的名称相同。

继承 yii\db\ActiveRecord 类;

在模型类中 声明 tableName() 指定表名 // 必须是静态方法

使用{{%表名}} 制定表前缀

<?php

namespace app\models;
use yii\db\ActiveRecord;

class Test extends ActiveRecord{
    public static function tableName(){
        // return "yii_test"; 返回我们的表名称
        // 由于我们以及在配置文件中进行配置了表前缀
        // 所以我们可以去掉 yii_ 使用双花括号 以及 % 来替代表前缀
        return "{{%test}}";
    }
}

 模型的使用:

创建完成之后,我们可以使用该模型进行数据查询:

$model->find()->one(); 返回一条结果;

首先返回我们的 IndexController 控制器,引入我们的 model

use app\models\Test;

进行实例化我们的model类:

<?php

namespace app\controllers;
use yii\web\Controller;
use app\models\Test;

class IndexController extends Controller{
    public function actionIndex(){
        $model = new Test;
        $result = $model->find()->one();
        // var_dump($result);
        return $this->render('index',array('data'=>$result));
    }
}

将查询的数据渲染到模板:

$this->render("index",array('data'=>$data));

这里渲染到模板,$data 是一个对象。

在模板中输出 $data 数据:

 

猜你喜欢

转载自www.cnblogs.com/e0yu/p/9944452.html