yii数据库基本操作
jianfly.com 2019-01-31 1732次浏览
<?php //创建数据模型 models namespace app\models; use yii\db\ActiveRecode; class Test extends ActiveRecode { } //控制器 controllers use app\models\Test; $sql = 'select * from text where id=1'; $results = Test::findBySql($sql)->all(); $sql = 'select * from text where id=:id'; $results = Test::findBySql($sql, array(':id'=>1))->all(); $results = Test::find()->where(['id'=>1])->all(); $results = Test::find()->where(['>', 'id', 0])->all(); $results = Test::find()->where(['between', 'id', 1, 2])->all(); $results = Test::find()->where(['like', 'title', 'title1'])->all(); //查询结果转化成数组 $results = Test::find()->where(['like', 'title', 'title1'])->asArray()->all(); //批量查询 foreach( Test::find()->batch(2) as $tests ) { print_r(count($tests)); } //删除数据 $results = Test::find()->where(['id'=>1])->all(); $results[0]->delete(); Test::deleteAll('id>0'); Test::deleteAll('id>:id', array(':id'=>0)); //模型中验证数据格式 public function rules() { return [ ['id', 'integer'], ['title', 'string', 'length'=>[0, 5]] ] } //添加数据 $test = new Test; $test->id = 3; $test->title = 'title3'; $test->validate();//调用验证 if($test->hasErrors()) { echo 'data is error!'; exit; } $test->save(); //单表数据修改 $test = Test::find()->where(['id'=>4])->one(); $test->title = 'title4'; $test->save(); //关联查询 //根据顾客查询订单信息 use app\models\Customer; use app\models\Order; $customer = Customer::find()->where(['name'=>'zhangsan'])->one(); $orders = $customer->hasMany('app\models\Order', ['customer_id'=>'id'])->all(); $orders = $customer->hasMany(Order::className(), ['customer_id'=>'id'])->all();//改进 //model改进封装 public function getOrders() { $orders = $this->hasMany(Order::className(), ['customer_id'=>'id'])->asArray()->all(); return $orders; } $orders = $customer->getOrders();//控制器中调取 //再改进 public function getOrders() { $orders = $this->hasMany(Order::className(), ['customer_id'=>'id'])->asArray(); return $orders; } $orders = $customer->orders;//访问不存在的属性时,调用__get(),调用getOrders(),补上all()方法 //根据订单查询顾客 public function getCustomer() { return $this->hasOne(Customer::className(), ['id']=>['customer_id'])->asArray(); } $order = Order::find()->where(['id'=>1])->one(); $customer = $order->getCustomer()->one(); $customer = $order->customer; //关联查询结果缓存 $customer = Customer::fimd()->where(['name'=>'zhangsan'])->one(); $orders = $customer->orders;//执行select * form order where customer_id = ... unset($customer->orders);//释放缓存 $orders2 = $customer->orders;//重新查询 //关联查询的多次查询 $customers = Customer::find()->all();//执行select * from customer foreach ($customers as $customer ) { $orders = $customer->orders;//执行select * form order where customer_id = ... }//执行n+1次查询 $customers = Customer::find()->with('orders')->all();//select * form customer; select * form order where customer_id in (...) foreach ($customers as $customer ) { $orders = $customer->orders;//不执行select }//执行2次