您的位置:首页 > 编程语言 > PHP开发

yii框架操作数据库的一种方式

2016-10-08 00:00 519 查看
使用active record

<?php

namespace app\controllers;

use yii\web\Controller;
use yii\data\Pagination;
use app\models\Country;

class CountryController extends Controller
{
public function actionIndex()
{
$query = Country::find();
$pagination = new Pagination([
'defaultPageSize' => 3,
'totalCount' => $query->count(),
]);

$countries = $query->orderBy('name')
->offset($pagination->offset)
->limit($pagination->limit)
->all();
//第一个参数为视图层,第二个为具体数据
return $this->render('index', [
'countries' => $countries,
'pagination' => $pagination,
]);
}
}

?>

country的model

<?php
namespace app\models;
use yii\db\ActiveRecord;

class Country extends ActiveRecord{

}
?>

简单的方式

<?php
namespace app\controllers;

use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\filters\VerbFilter;
use app\models\LoginForm;
use app\models\ContactForm;
use app\models\Country;
//use yii\db\ActiveRecord;

class IndexController extends Controller{
public function actionIndex(){
echo "hello";
//$country = Country::find()->orderBy('name')->all();
//var_dump($country);
$country = Country::findOne('US');
echo $country->name;

$country->name = 'U.S.A';
$country->save();
}
public function actionUsers(){
//查询
$sql = "select * from `user`";
$users = Yii::$app->db->createCommand($sql)->queryAll();
var_dump($users);
//增加数据
//			$sql = "insert into `user` (`name`,`sex`,`age`)values('杜春宝','男',25)";
//			$res = Yii::$app->db->createCommand($sql)->execute();
//			var_dump($res);
//删除操作
//			$sql = "delete from `user` where id=4";
//			$res = Yii::$app->db->createCommand($sql)->execute();
//			var_dump($res);
//
}
}
?>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  yii框架操作mysql