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())