Yii2学习笔记六:数据库操作
一、数据库查询
$sql='select * from test where id=:id'; $results=Test::findBySql($sql,[':id'=>1])->all();
$results=Test::find()->where('id=:id',[':id'=>1])->asArray()->all();
//批量查询 foreach(Test:find()->batch(2) as $test){ print_r($test); }
二、数据库删除
$results=Test::deleteAll('id>:id',['id'=>0]);
三、数据库添加
$test=new Test(); $test->id=3; $test->title='3' $test->validate(); if($test->hasErrors()){ echo 'error'; } $test->save();
四、数据库修改
$test=Test::find()->where('id=:id',[':id'=>1])->one(); $test->id=3; $test->title='3' $test->save();
$test=Test::updateAll('id=:id')
五、数据库关联查询
$test=Test::find()->where('id=:id',[':id'=>1])->one(); $test->orders
public function getOrders(){ return $this->hasMary(Order::className(),['order_id'=>'id']); }
$test=Test::find()->where('id=:id',[':id'=>1])->one(); $test->job;
public function getJob(){ return $this->hasOne(Job::className(),['job_id'=>'id']); }
//性能优化 //1.查询结果缓存 unset($test->order); $test->order //2.多次查询 foreach(Test::find()->width('orders')->all as $test){ $test->orders; }
文章
总共 0 条评论