使用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);
//
}
}
?>