Laravel 5.1 프레임 워 크 데이터베이스 조회 구축 기 사용법 실례 상세 설명

본 논문 의 사례 는 Laravel 5.1 프레임 워 크 데이터베이스 조회 구축 기 용법 을 서술 하 였 다.여러분 께 참고 하도록 공유 하 겠 습 니 다.구체 적 으로 는 다음 과 같 습 니 다.
오늘 은 검색 구축 기 에 대해 이야기 합 시다.그것 은 원생 SQL 을 실행 하 는 것 보다 간단 하고 조작 면 도 비교적 광범 위 하 다.
1 조회 결과
먼저 그의 문법 을 살 펴 보 자.

  public function getSelect()
  {
    $result = DB::table('articles')->get();
    dd($result);
  }

검색 구축 기 는 table 방법 으로 돌아 갑 니 다.get()을 사용 하면 결과 집합(array 형식)을 되 돌려 줍 니 다.여 기 는 모든 데 이 터 를 되 돌려 줍 니 다.물론 많은 제약 을 연결 할 수 있 습 니 다.
1.1 열/줄 데이터 가 져 오기

  public function getSelect()
  {
    $result = DB::table('articles')->where('title', 'learn database')->get();  //       
    $articles = DB::table('articles')->where('title', 'learn database')->first(); //       
    dd($result, $articles);
  }

우 리 는 where 를 통 해 조건 을 추가 할 수 있다.
1.2 데이터 열 값 목록 가 져 오기
열 값 을 찾 으 려 면 lists 방법 을 사용 하 십시오:

  public function getSelect()
  {
    $result = DB::table('articles')->where('id', '<', 2)->lists('title');
    $titles = DB::table('articles')->lists('title');
    dd($result, $titles);
  }

1.3 그룹 블록 결과 집합 가 져 오기
우리 데이터 시트 에서 데이터 가 매우 많 을 때 그룹 블록 결과 집합 을 사용 할 수 있 습 니 다.

  public function getSelect()
  {
    DB::table('articles')->chunk(2, function ($articles){
      foreach ($articles as $article){
        echo $article->title;
        echo "<br />";
      }
    });
  }

블록 실행 을 중지 하 겠 다 면 false 로 돌아 가면 됩 니 다.

  public function getSelect()
  {
    DB::table('articles')->chunk(2, function ($articles){
      return false;
    });
  }
1.4 중합 함수
구축 기 는 우리 가 사용 할 수 있 도록 많은 실 용적 인 방법 을 제공 했다.
  • count 방법:빌 더 가 조회 한 데 이 터 량 을 되 돌려 줍 니 다
  • 4.567917.max 방법:이 열 에서 가장 큰 값 을 되 돌려 줍 니 다
  • min 방법:max 방법 과 유사 하여 가장 작은 값 을 되 돌려 줍 니 다
  • sum 방법:열 값 을 더 한 합 을 되 돌려 줍 니 다
  • avg 방법:평균 값 을 계산 합 니 다1.4.1 count
    
      public function getArticlesInfo()
      {
        $article_count = DB::table('articles')->count();
        dd($article_count);
      }
    
    
    1.4.2 max
    
      public function getArticlesInfo()
      {
        $maxCommentCount = DB::table('articles')->max('comment_count');
        dd($maxCommentCount);
      }
    
    
    1.4.3 sum
    
      public function getArticlesInfo()
      {
        $commentSum = DB::table('articles')->sum('comment_count');
      }
    
    
    1.4.4 avg
    
      public function getArticlesInfo()
      {
        $commentAvg = DB::table('articles')->avg('comment_count');
        dd($commentAvg);
      }
    
    
    1.5 select 조회
    1.5.1 사용자 정의 자구
    selection 문 구 는 지정 한 열 을 가 져 올 수 있 고 사용자 정의 키 를 가 져 올 수 있 습 니 다.
    
      public function getArticlesInfo()
      {
        $articles = DB::table('articles')->select('title')->get();
        //     :
    //    array:3 [
    //      0 => {#150 
    //          +"title": "laravel database"
    //      }
    //      1 => {#151 
    //          +"title": "learn database"
    //       }
    //       2 => {#152 
    //          +"title": "alex"
    //       }
    //      ]
        $articles1 = DB::table('articles')->select('title as articles_title')->get();
        //     :
    //    array:3 [
    //       0 => {#153 
    //          +"articles_title": "laravel database"
    //       }
    //       1 => {#154 
    //          +"articles_title": "learn database"
    //       }
    //       2 => {#155 
    //          +"articles_title": "alex"
    //       }
    //      ]
        $articles2 = DB::table('articles')->select('title as articles_title', 'id as articles_id')->get();
    //    array:3 [
    //       0 => {#156 
    //          +"articles_title": "laravel database"
    //          +"articles_id": 1
    //       }
    //       1 => {#157 
    //          +"articles_title": "learn database"
    //          +"articles_id": 2
    //       }
    //       2 => {#158 
    //          +"articles_title": "alex"
    //          +"articles_id": 3
    //       }
    //      ]
      }
    
    
    1.5.2 distinct 방법
    distinct 방법 에 대해 서 는 무슨 뜻 인지 아직 모 르 겠 습 니 다.어떤 장면 에 적용 되 는 지,그리고 신 들 의 답 을 환영 합 니 다.감사합니다.
    distinct 방법 은 중복 되 지 않 는 결과 집합 을 강제로 조회 할 수 있 도록 합 니 다.
    
      public function getArticlesInfo()
      {
        $articles = DB::table('articles')->distinct()->get();
      }
    
    
    1.5.3 addSelect 방법
    select 를 추가 하려 면 이렇게 할 수 있 습 니 다.
    
      public function getArticlesInfo()
      {
        $query = DB::table('articles')->select('title as articles_title');
        $articles = $query->addSelect('id')->get();
        dd($articles);
      }
    
    
    2 where 구문
    where 문 구 는 비교적 자주 사용 되 는 것 으로 항상 그 로 조건 부 선별 을 한다.
    2.1 기초 소개
    이제 where 방법 을 자세히 소개 하 겠 습 니 다.세 개의 인 자 를 받 습 니 다.
    4.567917.열 명,이 건 할 말 이 없어 요
  • 데이터베이스 시스템 이 지원 하 는 연산 자,예 를 들 어'=',','like'등 이 있 습 니 다.두 번 째 매개 변 수 를 입력 하지 않 으 면 기본 값 은'='과 같 습 니 다
  • 비교 할 값
    
      public function getArticlesInfo()
      {
        $articles1 = DB::table('articles')->where('id','2')->get();     //   
        $articles2 = DB::table('articles')->where('id','>','2')->get();   //   
        $articles3 = DB::table('articles')->where('id','<>','2')->get();  //    
        $articles4 = DB::table('articles')->where('id','<=','2')->get();  //     
        $articles5 = DB::table('articles')->where('title','LIKE','%base')->get();  //   
      }
    
    
    2.2 orWhere
    orWhere 와 where 가 받 은 매개 변 수 는 같 습 니 다.where 논리 가 되 돌아 오 는 or 의 결 과 를 찾 지 못 했 을 때 where 가 찾 았 을 때 or 도 되 돌아 오 는 결 과 를 찾 았 습 니 다.
    
      public function getArticlesInfo()
      {
        $articles = DB::table("articles")->where('id','=','5')->orWhere('title','laravel database')->get();
        dd($articles);
      }
    
    
    2.where Between 과 where NotBetween
    where Between 은 열 값 이 주어진 값 사이 에 있 는 지 여 부 를 말 합 니 다.
    
      public function getArticlesInfo()
      {
        $articles = DB::table("articles")->whereBetween('id', [1, 3])->get();
        dd($articles);
      }
    
    
    ↑상기 코드 는 id 가 1~3 사이 에 있 는 집합 을 찾 는 것 입 니 다.
    where NotBetween 과 where Between 은 반대 입 니 다.
    
      public function getArticlesInfo()
      {
        $articles = DB::table("articles")->whereNotBetween('id', [1, 3])->get();
        dd($articles);
      }
    
    
    ↑상기 코드 는 id 가 1~3 사이 에 없 는 집합 을 찾 는 것 입 니 다.
    2.4 where in 과 where Notin
    wherein 은 주어진 데이터 에서 열 값 을 찾 습 니 다:
    
      public function getArticlesInfo()
      {
        $articles = DB::table("articles")->whereIn('id', [1, 3, 5, 8])->get();
        dd($articles);
      }
    
    
    ↑상기 코드 에 서 는 ID 가 1,3,5,8 인 집합 을 찾 습 니 다.그러나 우리 데이터베이스 에 id 가 1 과 3 인 데이터 만 있 으 면 id 가 1 과 3 인 집합 만 되 돌려 줍 니 다.
    where Notin 과 where in 의 반대:
    
      public function getArticlesInfo()
      {
        $articles = DB::table("articles")->whereNotIn('id', [1, 3, 5, 8])->get();
        dd($articles);
      }
    
    
    ↑위 코드 에 서 는 ID 찾기 가 1,3,5,8 의 집합 이 아 닙 니 다.
    2.5 where Null 과 where NotNull
    whereNull 은 열 값 이 비어 있 는 데 이 터 를 찾 습 니 다:
    
      public function getArticlesInfo()
      {
        $articles = DB::table("articles")->whereNull('created_at')->get();
        dd($articles);
      }
    
    
    ↑상기 코드 에서 created 찾기at 빈 집합.
    where NotNull 은 말 할 필요 가 없습니다.
    
      public function getArticlesInfo()
      {
        $articles = DB::table("articles")->whereNotNull('created_at')->get();
        dd($articles);
      }
    
    
    ↑상기 코드 에서 created 찾기at.빈 집합 이 아 닙 니 다.
    3 데이터 삽입
    가장 간단 한 삽입 방법 을 먼저 보 세 요:
    
      public function getInsertArticle()
      {
        //       :
        DB::table('articles')->insert(
          ['title'=>'get more', 'body'=>'emmmmmm......']
        );
        //       :
        DB::table('articles')->insert([
          ['title'=>'testTitle1', 'body'=>'testBody1'],
          ['title'=>'testTitle2', 'body'=>'testBody2'],
          // ....
        ]);
      }
    
    
    데 이 터 를 삽입 하 는 ID 를 받 으 려 면 다음 과 같은 추가 ID 를 가 져 오 는 방법 을 사용 할 수 있 습 니 다.
    
      public function getInsertArticle()
      {
        //       :
        $id = DB::table('articles')->insertGetId(
          ['title'=>'get more', 'body'=>'emmmmmm......']
        );
        dd($id);
      }
    
    
    업데이트
    
      public function getUpdateArticle()
      {
        $result = DB::table('articles')->whereBetween('id', [1, 3])->update(['comment_count'=>0]);
        dd($result);
      }
    
    
    ↑update 는 몇 가지 데 이 터 를 되 돌려 줄 수 있다.
    4.1 단축 키 추가/감소 방법
    
      public function getUpdateArticle()
      {
        $result = DB::table('articles')->whereBetween('id', [1, 3])->increment('comment_count',2);
        dd($result);
      }
    ↑increment 는 1~2 개의 인 자 를 받 아들 이 고 첫 번 째 인 자 는 열 명 이 며 두 번 째 인 자 는 선택 할 수 있 는 표시 가 몇 개 증가(기본 값 은 1)입 니 다.위의 문 구 는 comment 입 니 다.count 이 열의 값 이 2 증가 합 니 다.
    
      public function getUpdateArticle()
      {
        $result = DB::table('articles')->whereBetween('id', [1, 3])->decrement('comment_count',2);
        dd($result);
      }
    
    
    ↑decrement 는 1~2 개의 인 자 를 받 아들 이 고 첫 번 째 인 자 는 열 명 이 며 두 번 째 인 자 는 선택 할 수 있 는 표시 감소 몇(기본 값 은 1)입 니 다.위의 문 구 는 comment 입 니 다.count 이 열의 값 이 2 감소 합 니 다.
    너 는 가감 단축 방법 이 두 개의 매개 변수 만 받 을 것 이 라 고 생각 하 니?nonono 는 세 번 째 인 자 를 받 을 수 있 습 니 다.
    
      public function getUpdateArticle()
      {
        $result = DB::table('articles')->whereBetween('id', [1, 3])->increment('comment_count', 2, ['title' => 'testUpdate']);
        dd($result);
      }
    
    
    ↑그것 은 또한 증가/감소 시 다른 열 을 수정 할 수 있다.
    삭제
    
      public function getDeleteArticle()
      {
        $result = DB::table('articles')->whereBetween('id', [1, 3])->delete();
        dd($result);
      }
    
    
    ↑delete 로 데 이 터 를 삭제 하면 몇 줄 이 영향 을 받 는 지 되 돌려 줍 니 다.
    모든 열 을 삭제 하고 자 증 된 ID 를 0 으로 돌 리 려 면 이렇게 할 수 있 습 니 다.
    
      public function getDeleteArticle()
      {
        DB::table('articles')->truncate();
      }
    
    
    자물쇠
    검색 구축 기 는 selection 구문 에서'비관 적 잠 금'을 실현 하 는 데 도움 을 주 는 방법 도 포함 되 어 있다.검색 에서 shared Lock 방법 을 사용 하여 문 구 를 실행 할 때'공유 자물쇠'를 가 져 올 수 있 습 니 다.공유 자 물 쇠 는 트 랜 잭 션 이 제출 될 때 까지 선택 한 줄 이 수정 되 는 것 을 피 할 수 있 습 니 다:
    
    DB::table('articles')->where('id', '>', 100)->sharedLock()->get();
    
    
    "그리고 lockForUpdate 방법 도 사용 할 수 있 습 니 다."for update"자 물 쇠 는 선택 줄 이 다른 공유 자물쇠 에 의 해 수정 되 거나 삭제 되 는 것 을 피 합 니 다:
    
    DB::table('articles')->where('id', '>', 100)->lockForUpdate()->get();
    
    
    Laravel 관련 내용 에 관심 이 있 는 독자 들 은 본 사이트 의 주 제 를 볼 수 있다.
    본 고 는 Laravel 프레임 워 크 를 바탕 으로 하 는 PHP 프로 그래 밍 에 도움 이 되 기 를 바 랍 니 다.

    좋은 웹페이지 즐겨찾기