初学YII
安装Yii
通过composer安装
composer create-project --prefer-dist yiisoft/yii2-app-basic basic
安装完成会有一个 basic
目录
进入目录运行
cd basic
php yii serve
在页面打开查看
控制器
新建一个控制器
namespace app\controller;
use yii\web\Controller;
class HelloController extends Controller
{
public function actionIndex()
{
}
}
数据模型
数据模型对应数据表 ORM
模型与表关系映射
namespace app\models;
use yii\db\ActiveRecord;
class Test extends ActiveRecord
{
// 模型操作的表
public static function tableName()
{
// 默认是返回模型对应的表
//return 'test';
}
}
单表查询
namespace app\controller;
use yii\web\controller;
use app\models\Test;
class HelloController extends Controller
{
public function actionIndex()
{
$sql = 'select * from where id=1';
$result = Test::findBySql($sql)->all();
//条件查询
$resul2 = Test::find()->where(['id'=>1])->all();
// 查询结果转出数组
$resul3 = Test::find()->where(['id'=>1])->asArray->all();
// 批量查询 batch 2条
foreach(Test::find()->batch(2) as $tests) {
print_r($tests);
}
}
}
数据表操作
namespace app\controller;
use yii\db\ActiveRecord;
class ApiController extends ActiveRecord
{
public function actionNews()
{
$sql = 'select * from news';
$res = \YII::$app->db->createCommand($sql)->queryAll();
print_r($res);
}
public function actionStudent()
{
$query = new \yii\db\Query();
$rows = $query->from('students')->select()->all();
}
}
删除数据
namespace app\controller;
use yii\web\controller;
use app\models\Test;
class HelloController extends Controller
{
public function actionIndex()
{
//删除数据
$res = Test::find()->where(['id'=>1])->all();
$res[0]->delete();
Test::deleteAll('id>:id', [':id'=>1]);
Test::deleteAll();
}
}
添加数据
namespace app\controller;
use yii\web\controller;
use app\models\Test;
class HelloController extends Controller
{
public function actionIndex()
{
$test = new Test();
// 字段赋值
$test->id = 3;
$test->title = 'title3';
// 校验数据 rules
$test->validate();
if(!$test->hasError()) {
$test->save();
}
}
}
namespace app\models;
use yii\db\ActiveRecord;
class Test extends ActiveRecord
{
public static function tableName()
{
// 默认是返回模型对应的表
//return 'test';
}
// 验证器,验证数据
public function rules()
{
return [
['id', 'integer'],
['title', 'string', 'length'=>[0,5]]
];
}
}
修改数据
$test->save()
关联表查询
hasMany()
hasOne()
视图
视图目录:views/layout/xxx
public function actionIndex()
{
$layout = 'common'; // 公共视图
return $this->render('index'); //$content 默认代表视图文件的内容
}
index.php
hello index
common.php
<html>
<title></title>
<body>
<h1>
heihei
</h1>
<?=$content?>
</body>
</html>
在一个视图中显示另一个视图
about.php
<h1>
hello about.php
</h1>
<?php $this->render('index') ?>
数据块
index.php
<h1>
index
</h1>
<?php $this->beginBlock('block1');?>
<title>哈哈哈哈哈</title>
<?php $this->endBlock() ?>
common.php
<html>
<head>
</head>
<body>
<?=$this->blocks['block1']?>
<?=$content?>
</body>
</html>