学习yii2.0——数据库
以组件方式操作数据库
用这种方式的话,应该配置数据库组件。比如平时用的主从数据库:masterDb和slaveDb,都可以配置成单独的组件。
配置数据库组件,可以在config/web.php中的$config的component项中添加。
'components' => [
"masterDb" => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=192.168.1.2;dbname=test',
'username' => 'root',
'password' => 'root',
'charset' => 'utf8',
],
"slaveDb" =>[
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=192.168.1.3;dbname=test',
'username' => 'root',
'password' => 'root',
'charset' => 'utf8',
]
]
那么在使用配置的数据库组件的时候,可以这样用:
<?php
namespace app\controllers;
use Yii;
use yii\web\Controller;
class HelloController extends Controller {
public function actionIndex()
{
$masterDb = Yii::$app->masterDb;
$slaveDb = Yii::$app->slaveDb;
//执行查询
//queryXyz()会以数组格式返回
$all = $slaveDb->createCommand("select * from stu")->queryAll();
$one = $slaveDb->createCommand("select * from stu")->queryOne();
//执行增删改
//execute() 返回受影响的记录数
$affected_rows = $masterDb->createCommand("update stu set name='xyz' where id = 1")->execute();
//使用预处理
$command = $masterDb->createCommand("select * from stu where id=:id and gender=:gender");
//一次绑定一项
// $command->bindValue(":id", 1);
// $command->bindValue(":gender", "male");
//一次绑定多项
$command->bindValues(array(":id"=>2, "gender"=>"female"));
$res = $command->queryAll();
//事务
$transaction = $masterDb->beginTransaction();
try {
$affected_1 = $masterDb->createCommand("update stu set name=':name' where id=':id'")
->bindValues([":name" => "aaaaa", ":id" => 1])
->execute();
$affected_2 = $masterDb->createCommand("update stu set name=':name' where id=':id'")
->bindValues([":name" => "aaaaa", ":id" => 999999])
->execute();
if ($affected_1 && $affected_2) {
$transaction->commit();
} else {
throw new \Exception("failed to run sql");
}
} catch (\Exception $e){
$transaction->rollback();
echo $e->getMessage();
}
}
}
配置数据库
数据库配置文件的路径是config/db.php;
<?php
return [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=test',
'username' => 'root',
'password' => '123456',
'charset' => 'utf8',
];
如果在连接数据库的时候,出现问题,那么可以尝试将localhost改为127.0.0.1。
使用查询构造器
使用查询构造器之前要先配置数据库,会使用上面db.php中的配置。
<?php
namespace app\controllers;
use Yii;
use yii\web\Controller;
use yii\db\Query; //导入查询构造器类
class HelloController extends Controller {
public function actionIndex()
{
$queryBuilder = new Query();
$res = $queryBuilder->select(["name", "gender"])
->from("stu")
->where("id=:id",[":id" => 2])
->orderBy(["id" => SORT_ASC])
->limit(1)
->all();
print_r($res);
}
}
数据表
假设数据库里面有一个stu表,包含数据如下:
mysql> desc stu; +--------+----------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +--------+----------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | name | char(30) | NO | | NULL | | | gender | char(10) | NO | | male | | +--------+----------+------+-----+---------+----------------+ 3 rows in set (0.13 sec)
创建数据模型
yii中定义的模型,有一类很特别,称之为ActiveRecord。每一个继承这个类的模型都有以下特点:
1、模型(类名)和数据库中的表名保持一致(也可以不一致,可以修改)。
2、可以通过类名来实现对数据表的增删改查。
<?php
namespace app\models;
use yii\db\ActiveRecord;
class Student extends ActiveRecord {
//指定当前模型和哪个表进行关联
//如果不重写的话,默认是与类名相同的表名进行关联
public static function tableName()
{
return '{{stu}}';
}
//指定当前模型与数据库进行连接的时候,使用哪个数据库配置
//如果不重写的话,默认是使用\Yii::$app->db组件。
public static function getDb()
{
return \Yii::$app->masterDb;
}
}
使用数据模型
在find()后面可以使用和QueryBuilder同样的方法。
<?php
namespace app\controllers;
use Yii;
use yii\web\Controller;
use app\models\Student;
class HelloController extends Controller {
public function actionIndex()
{
//类似于
$res = Student::find()->where("id=:id", [":id"=>1])->asArray()->all();
//匹配主键,返回一条记录,结果是对象集合
$stu = Student::findOne(["name" => "abc", "gender" => "female"]);
if ($stu) { //如果记录不存在
echo $stu->id;
echo $stu->name;
echo $stu->gender;
$stu->name = "aaaaa";
$stu->gender = "male";
$stu->save(); //修改该条记录
} else {
//echo "数据不存在";
$stu = new Student();
$stu->name = "abc";
$stu->gender = "female";
$stu->save(); //添加记录
}
//执行SQL,并且绑定SQL语句
$res = Student::findBySql("select * from stu where id>:id", [":id" => "0"])->asArray()->all();
print_r($res);
}
}
如需转载,请注明文章出处,谢谢!!!
浙公网安备 33010602011771号