YII学习之简单数据交互
学完了表单的创建和数据提交,今天主要就是学习如何与数据库的交互。
首先配置数据库的基本信息[config/db.php]
<?php
return [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=test',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
];
视图代码还是上一次的,这里就不帖上了。
控制器 [IndexController.php]
<?php
namespace app\controllers;
use Yii;
use yii\web\controller;
use app\models\Entry;
class IndexController extends controller
{
public function actionEntry()
{
//关闭页面布局
$this->layout = false;
//创建表单模型
$entry = new Entry;
//如果是Post请求提交
if(Yii::$app->request->getIsPost()){
//表单模型设置属性为post值
$entry->setAttributes(Yii::$app->request->post());
//表单模型数据验证
if ($entry->validate()) {
//正确即保存数据
$result = $entry->save();
//返回保存后的信息
if($result){
var_dump($entry->attributes);
}else{
var_dump($entry->getErrors());
}
} else {
//返回错误提示
var_dump($entry->getErrors());
}
}else{
//如果不是Post请求,正常显示模板
return $this->render('entry',['model'=>$entry]);
}
}
public function actionDb()
{
//查询指定单条数据
$entry = Entry::findOne(85);
echo $entry->id;
//保存指定数据
$entry->name = 'hoogl';
$entry->email= 'hoogl@126.com';
$entry->save();
//查询多条数据
$list = Entry::find()->OrderBy(['id'=>SORT_ASC])->all();
var_dump($list);
//删除指定数据
Entry::findOne(84)->delete();
//删除多条数据
Entry::deleteAll('name = :name AND id > :id', [':id' => 80, ':name' => 'hoogl']);
}
}
模型 [Entry.php]
<?php
namespace app\models;
use yii\db\ActiveRecord;
class Entry EXTENDS ActiveRecord{
//默认类名即数据表名,这里重新定义数据表名
public static function tableName()
{
return '{{user}}';
}
public function rules()
{
return [
[['name','email'],'required','message'=>'请填写!'],
['email','email','message'=>'邮箱格式不正确!']
];
}
}
这里有一个坑,我是按照中文社区里面的教程http://www.yiichina.com/doc/guide/2.0/start-forms,模型里面定义了name和email变量,在控制器里面用save方法保存的时候,一直返回true,就是表单数据没有录入到数据,但是,又生成了新记录。
调试代码发现:
private '_attributes' (yii\db\BaseActiveRecord) =>
array (size=0)
empty
_attributes这个变量一直是empty,查看源码baseActiveRecord.php发现_attributes是靠魔术方法__set来把变量名称和值保存进_attrbutes中的,而我在模型里面定义了变量名称,所以,一直没有走这个魔术方法。
解决办法:删除模型里面的public $name和public $email即可。