Yii数据库基本操作
2017-02-24 17:03
471 查看
1、单表查询
<?php namespace frontend\controllers; use \yii\web\Controller; use app\models\Test; class HelloController extends Controller{ public function actionIndex(){ //查询test表的数据 $sql = 'select * from test where id = 1'; //每条记录包装成对象,把对象包装成数组返回 //自带防sql注入 $result = Test::findBySql($sql)->all(); print_r($result); } }
简便方法
$result = Test::find() ->where(['Id' => '2']) ->all(); print_r($result); //查询id>0的数据 $result = Test::find() ->where(['>','Id','0']) ->all(); print_r($result); //查询id>= 1&&id<=2 $result = Test::find() ->where(['between','Id',1,2]) ->all(); //title like "%title2" $result = Test::find() ->where(['like','title','title2']) ->all();
访问http://lcc.com/index.php?r=hello/index可查询结果
其他类型,访问http://www.yiichina.com/doc/guide/2.0/db-active-record查询
降低内存占用
//对象方式返回很吃内存,所以Yii提供转化数组的方法,asArray() $result = Test::find() ->where(['>','Id','0']) ->asArray() ->all();
//批量查询
foreach (Test::find()->batch(2) as $result) { print_r($result);//一次查2条,结果放在$result中 }
2、单表删除
//删除数据$result = Test::find()->where(['Id' => '1'])->all(); $result[0]->delete(); Test::deleteAll('id>0');//删除大于0的行,同时,也支持占位符的功能
3、单表添加数据
//插入数据$test = new Test(); $test->Id = 'abc'; $test->title = 'title3';
//调用模型证rules验证器验证
$test->validate();
//如果输入数据不合法,输出‘data is error ’
if($test->hasErrors()){ echo 'data is error'; die; } $test->save();
模型中的验证器
public function rules() { return [ ['Id','integer'], ['title','string','length'=>[0,10]] ]; }
4、单表数据修改
// //修改数据$test = Test::find() ->where(['Id' => 5]) ->one(); $test->title = 'testtitle'; $test->save();
5、关联查询
//根据顾客查询订单的信息$customer = Customer::find()->where(['id'=>1])->one(); //$order = $customer->hasMany('app\models\Order',['customer_id' => 'id'])->asArray()->all(); $order = $customer->hasMany(Order::className(),['customer_id' => 'id'])->asArray()->all(); print_r($order);
优化:
$customer = Customer::find()->where(['id'=>1])->one(); //$order = $customer->getOrder(); $order = $customer->order;//原理:调用不存在的属性时,默认调用$__GET方法,脸上order,进而调用getorder print_r($order);
在Customer中添加getOrder方法
public function getOrder(){ $order = $this->hasMany(Order::className(),['customer_id' => 'id'])->asArray()->all(); return $order; }
//根据订单查询顾客
$order = Order::find()->where(['order_id'=>1])->one(); $customer = $order->customer; print_r($customer);
在Order中添加getCustomer方法
public function getCustomer(){ $customer = $this->hasOne(Customer::className(),['id'=>'customer_id'])->asArray()->one(); return $customer; }
6、关联查询性能问题
关联查询结果缓存关联查询的多次查询(用with())
相关文章推荐
- YII中的数据库基本操作语句
- 二:使用yii框架建立应用(数据库CURD基本操作)
- yii下数据库的基本操作
- 学习Asp.Net应当知道的基本数据库操作语句
- Java数据库基本操作
- 数据库中表的基本操作
- ADO.net 中 数据库操作的基本方法
- 对数据库的几种基本操作
- 学习Asp.Net应当知道的基本数据库操作语句
- ASP.NET对数据库的基本操作——插入,删除,修改(下)
- PHP中数据库基本操作
- java数据库操作基本流程
- java 数据库基本操作
- 对数据库中列的一些基本的操作的SQL命令
- java数据库基本操作指南
- 数据库几个基本操作
- ORACEL数据库基本操作
- 1、java数据库操作基本流程
- java 数据库基本操作
- java数据库操作基本流程