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

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())
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: