<?php
/**
- 活动记录的创建
*/
namespace app\models;
use yii\db\ActiveRcord;
class Test extends ActiveRecord
{
public function __construct(argument)
{
# code...
}
}
/**
- 活动记录的单表查询
*/
namespace app\controllers;
use yii\web\Controller;
use app\models\Test;
class Test extends ActiveRecord
{
public function actionIndex()
{
//查询数据
$sql = 'select * from test where id=1';
$results = Test::findBySql()->all(); //返回的记录都会包装为一个对象
//安全,占位
$results = Test::find()->where(['id'=>1])->all();
//id>0
$results = Test::find()->where(['>','id', 0])->all();
//id>=1 并且 id<=2
$results = Test::find()->where(['between','id', 1, 2])->all();
//title like "%title1%"
$results = Test::find()->where(['like','title', 'title1'])->all();
//查询结果转化成数据,降低内存占有
$results = Test::find()->where(['like','title', 'title1'])-asArray()->all();
//批量查询,降低内存占有
foreach(Test::find()->batch(2) as $tests){
print_r(count($tests));
}
//单表删除
$results = Test::find()->where(['id'=>1])->all();
$results[0]->delete(); //删除单条记录
Test::deleteAll('id>:id',array(':id'=>0)); //删除数据
//单表添加数据, 可以在Test的model添加rules规则来验证数据
$test = new Test;
$test->id = 3;
$test->title = 'title3';
$test->validate();
if($test->hasErrors){
echo 'error';
die;
}
$test->save();
//单表数据修改
$test = Test::find()->where(['id'=>4])->one();
$test->title = 'title4';
$test->save();
print_r($results);
}
}