YII 2 데이터베이스 조회 실천

yii 2 프레임 워 크 를 탐색 하고 첨삭 검사,관련 조회 등 데이터 베이스 기본 작업 에 대한 간단 한 실천.
데이터베이스 설정.
데이터베이스 설정
실천 과정 중 에 테스트 라 이브 러 리-테스트 표-두 가지 기록 은 다음 과 같다

mysql> select * from test;
+----+--------+
| id | name |
+----+--------+
| 1 | zhuai |
| 2 | heng | 
+----+--------+
18 rows in set (0.00 sec)
sql 조회 방식
yii 2 는 원본 데이터베이스 조회 방식 findBySql 을 제공 합 니 다.또한,자리 표시 자 를 통 해 기본 sql 주입 방 어 를 자동 으로 진행 합 니 다.상등품

//         
$sql = "select * from test where 1";
$res = Test::findBySql($sql)->all();
var_dump(count($res)); // res->2 
// findbysql   sql    
$id = '1 or 1=1';
$sql = "select * from test where id = " . $id;
$res = Test::findBySql($sql)->all();
var_dump(count($res)); // res-> 2
$sql = "select * from test where id = :id";
//         sql   
$res = Test::findBySql($sql,array(":id"=>$id))->all();
var_dump(count($res)); // res->1
activeRecord 조회 방식
모든 프레임 워 크 는 기 존의 sql 방식 을 제외 하고 해당 하 는 패 키 징 조회 방식 을 제공 합 니 다.yii 2 도 마찬가지 입 니 다.
모델 생 성
yii 의 model 기본 방식 은 다음 과 같 습 니 다.코드 는 다음 과 같 습 니 다.

<?php
namespace app\models;
use Yii;
use yii\db\ActiveRecord;
class Test extends ActiveRecord
{
//   ,   :         ,      
public static function tableName()
{
return 'test';
}
//   ,   :          
public function rules(){
return [
['id', 'integer'],
['name', 'string', 'length' => [0, 100]],
];
}
}
사용 할 때 model 을 도입 해 야 합 니 다.

use app\models\Test;
    
// add   
$test = new Test();
$test->name = 'test';
//      
$test->validate();
if($test->hasErrors()){
echo "     ";
die;
}
$test->save();
조회 조작
조회 작업 은 먼저 공식 문서 에 올 립 니 다.
activeRecord doc
where doc
강조해 야 할 것 은 yii 조 회 는 매우 풍부 한 라 이브 러 리 를 제공 합 니 다.예 를 들 어 코드 중의 대량 조회 처리 등 세부 사항 은 문 서 를 볼 수 있 습 니 다.

// select
// id = 1
$res = Test::find()->where(['id' => 1])->all();
var_dump(count($res)); //1
// id > 0
$res = Test::find()->where(['>','id',0])->all();
var_dump(count($res)); //2
// id > =1 id <=2
$res = Test::find()->where(['between','id',1,2])->all();
var_dump(count($res)); //2
// name  like
$res = Test::find()->where(['like', 'name', 'cuihuan'])->all();
var_dump(count($res)); //2
//       obj->array
$res = Test::find()->where(['between','id',1,2])->asArray()->all();
var_dump($res[0]['id']); //2
//     ,            
foreach (Test::find()->batch(1) as $test) {
var_dump(count($test));
}
삭제 작업

// delete 
//      
$res = Test::find()->where(['id'=>1])->all();
$res[0]->delete();
//     
var_dump(Test::deleteAll('id>:id', array(':id' => 2)));
조작 을 수정 하 다
코드 의 방식 을 제외 하고 yii 2 는 update 작업 을 직접 제공 합 니 다.

//       
$res = Test::find()->where(['id'=>4])->one();
$res->name = "update";
$res->save();
관련 조회 조작
관련 조회 예제 의 두 표:
학생 표(student):id,name;
점수 표(score):id,stuid,score

//        score
$stu = Student::find()->where(['name'=>'xiaozhuai'])->one();
var_dump($stu->id);
//     
$scores_1 = $stu->hasMany('app\model\Score',['stu_id'=>$stu->id])->asArray()->all();
$scores_2 = $stu->hasMany(Score::className(),['stu_id'=>'id'])->asArray()->all();
var_dump($scores_1);
var_dump($scores_2);
두 가지 관련 조회 방식;그러나 controller 에서 관련 조작 을 하면 코드 가 너무 혼 란 스 러 워 서 model 에서 호출 을 봉인 합 니 다.
우선 student model 에 관련 호출 함 수 를 패키지 합 니 다.

<?php
namespace app\models;
use Yii;
use yii\db\ActiveRecord;
class Student extends ActiveRecord
{
public static function tableName()
{
return 'student';
}
//       
public function getScores()
{
$scores = $this->hasMany(Score::className(), ['stu_id' => 'id'])->asArray()->all();
return $scores;
}
}
이후 직접 호출,두 가지 호출 방식

//         
$scores = $stu->getScores();
var_dump($scores);
//   __get         
$scores = $stu->scores;
var_dump($scores);
마지막.
위 에서 yii 2 의 배치 와 사용 과정 에서 의 기본 적 인 첨삭 검사,관련 조회 등 작업.

좋은 웹페이지 즐겨찾기