>  기사  >  php教程  >  Laravel 프레임워크 데이터베이스 CURD 작업 및 일관된 작업 사용

Laravel 프레임워크 데이터베이스 CURD 작업 및 일관된 작업 사용

高洛峰
高洛峰원래의
2016-11-22 12:40:471859검색

Laravel 프레임워크 데이터베이스 CURD 작업, 일관성 있는 작업 사용 방법
Laravel 프레임워크 데이터베이스 CURD 작업, 일관성 있는 작업 방법은 매우 편리하고 간단합니다. 아래에 단계가 소개되어 있습니다.
Laravel은 간단하고 우아한 PHP 웹 개발 프레임워크(PHP Web Framework)입니다. 누들과 같은 지저분한 코드에서 벗어날 수 있으며 완벽한 네트워크 앱을 구축하는 데 도움이 될 수 있으며 모든 코드 줄은 간결하고 표현력이 뛰어납니다.
1. 선택
테이블의 모든 행 검색
$users = DB::table('users')->get();
foreach($users를 $user로)
{
var_dump($user->name);
}
테이블에서 단일 행 검색
$user = DB::table('users')->where(' name' , 'John')->first();
var_dump($user->name);
단일 열에 대한 행 검색
$name = DB::table('users' )-> ;where('name', 'John')->pluck('name');
열 값 목록 검색
$roles = DB::table('roles')-> ;lists(' title');
이 메소드는 배열 제목을 반환합니다. 배열을 반환하도록 사용자 정의 키 열을 지정할 수도 있습니다.
$roles = DB::table('roles')->lists('title', 'name');

선택 지정 절
$users = DB::table('users')->select('name', 'email')->get();
$users = DB::table('사용자' )->distinct()->get();
$users = DB::table('users')->select('user_name으로 이름')->get();
기존 쿼리에 추가된 Select 절
$query = DB::table('users')->select('name');
$users = $query->addSelect( 'age')- >get();
where
$users = DB::table('users')->where('votes', '>', 100)->get();
OR
$users = DB::table('users')->where('votes', '>', 100)->orWhere('name', 'John' )->get ();

Where Between
$users = DB::table('users')->whereBetween('votes', array(1, 100))-> get();

Where Not Between
$users = DB::table('users')->whereNotBetween('votes', array(1, 100))->get() ;

배열이 있는 위치
$users = DB::table('users')->whereIn('id', array(1, 2, 3))->get( );
$users = DB::table('users')->whereNotIn('id', array(1, 2, 3))->get();

Where Null을 사용하여 레코드 찾기 값 설정 해제
$users = DB::table('users')->whereNull('updated_at')->get();

Order By, Group By, And Have
$users = DB::table('users')->orderBy('name', 'desc')->groupBy('count')->having('count', '> ;', 100) ->get();
오프셋 및 제한
$users = DB::table('users')->skip(10)->take(5)-> get();
2. 연결
조인
쿼리 빌더를 사용하여 연결 문을 작성할 수도 있습니다. 다음 예를 살펴보세요.
DB::table('users')
->join('contacts', 'users.id', '=', 'contacts.user_id')
- >join('orders', 'users.id', '=', 'orders.user_id')
->select('users.id', 'contacts.phone', 'orders.price) ')
->get();
왼쪽 조인 문
DB::table('users')
->leftJoin('posts', 'users.id', '= ', 'posts.user_id')
->get();
DB::table('users')
->join('contacts', function($join)
{
$join->on('users.id', '=', 'contacts.user_id')->orOn(...);
})
->get( );
DB::table('users')
->join('contacts', function($join)
{
$join->on('users.id' , ' =', 'contacts.user_id')
->where('contacts.user_id', '>', 5);
})
->get();

3. 그룹화
때로는 "exists" 또는 중첩된 매개변수 그룹화와 같은 고급 where 절을 만들어야 할 수도 있습니다. Laravel 쿼리 빌더는 다음을 처리할 수 있습니다:
DB::table('users')
->where('name', '=', 'John')
->orWhere(function($ 쿼리)
{
$query->where('votes', '>', 100)
->where('title', 'a8093152e673feb7aba1828c43532094', 'Admin') ;
})
->get();

위 쿼리는 다음 SQL을 생성합니다.
select * from users where name = 'John' 또는 (votes > 100 및 제목
a8093152e673feb7aba1828c43532094 'Admin')
Exists 문
DB::table('users')
->whereExists(function($query)
{
$query->select(DB::raw(1))
->from('orders')
->whereRaw('orders.user_id = users.id');
} )
->get();
위 쿼리는 다음 SQL을 생성합니다.
select * from userswhere presents(
orders.user_id = users.id인 주문에서 1 선택
)

4. 집계
쿼리 빌더는 통계, 최대, 최소, 평균, 합계 등 다양한 집계 방법도 제공합니다.
$users = DB::table('users')->count();
$price = DB::table('orders')->max('price');
$price = DB::table('orders')->min('price');
$price = DB::table('orders')->avg('price');
$total = DB::table('users')->sum('votes');
원시 표현식
때로는 원시 표현식 쿼리를 사용해야 할 수도 있습니다. 이러한 표현식은 쿼리 문자열에 삽입되므로 SQL 삽입 지점을 만들지 않도록 주의하세요! 원시 표현식을 생성하려면 DB:rawmethod:
원시 표현식 사용
$users = DB::를 사용할 수 있습니다. table(' 사용자')
->select(DB::raw('count(*) as user_count, status'))
->where('status', 'a8093152e673feb7aba1828c43532094', 1)
->groupBy('status')
->get();

열 값 증가 또는 감소

DB::table(' users')- >increment('votes');
DB::table('users')->increment('votes', 5);
DB::table('users')- >decrement( 'votes');
DB::table('users')->decrement('votes', 5);

추가 열 업데이트를 지정할 수도 있습니다.

DB::table('users')->increment('votes', 1, array('name' => 'John'));

삽입
다음에 레코드를 삽입합니다. 테이블
DB::table('users')->insert(
array('email' => 'john@example.com', 'votes' => 0)
) ;

자동 증가 ID를 사용하여 테이블에 레코드 삽입
테이블에 자동 증가 ID 필드가 있는 경우 insertGetId를 사용하여 레코드를 삽입하고 ID를 검색합니다.

$id = DB::table('users')->insertGetId(
array('email' => 'john@example.com', 'votes' => 0)
);


참고: PostgreSQL insertGetId 메서드를 사용할 때 자동 증가 열의 이름은 "id"로 지정될 것으로 예상됩니다.
테이블에 여러 레코드 삽입
코드는 다음과 같습니다.
DB::table('users')->insert(array(
array('email' => 'taylor) @example .com', 'votes' => 0),
array('email' => 'dayle@example.com', 'votes' => 0),
));

4. 업데이트
테이블의 레코드 업데이트
코드는 다음과 같습니다.
DB::table('users')
->where('id', 1 )
->update(array('votes' => 1));

5. 삭제
테이블의 레코드 삭제
코드는 다음과 같습니다.
DB::table('users')->where('votes', '72ab85c16fd8ed6098b5cdd7c2ff8778delete();

테이블의 모든 레코드를 삭제합니다
코드는 다음과 같습니다.
DB::table ('users')->delete();
테이블 삭제

코드는 다음과 같습니다.

DB::table ('users')->truncate();

6. Unions
쿼리 빌더는 두 쿼리를 "union"하는 빠른 방법도 제공합니다.

코드는 다음과 같습니다. :
$first = DB::table( 'users')->whereNull('first_name');
$users =
DB::table('users')->whereNull(' last_name')->union($first)- >get();

UnionAll 메소드도 사용 가능하며 동일한 메소드 서명을 갖습니다.
비관적 잠금
쿼리 빌더에는 SELECT 문에 도움이 되는 몇 가지 "비관적 잠금" 기능이 포함되어 있습니다. SELECT 문 "Shared Lock"을 실행하면 sharedLock 메서드를 사용하여 쿼리할 수 있습니다.
코드는 다음과 같습니다.
DB::table('users')->where('votes', '> ;',
100)->sharedLock()->get();
SELECT 문에서 "lock"을 업데이트하려면 lockForUpdate 메서드를 사용하여 다음을 쿼리할 수 있습니다.

코드

DB ::table('users')->where('votes', '>', 100)->lockForUpdate()->get();

7. 캐시 쿼리
니모닉을 사용하여 쿼리 결과를 쉽게 캐시할 수 있습니다.
코드는 다음과 같습니다.
$users = DB::table('users')-> Remember(10)->get();
이 예에서는 쿼리 결과가 10분 동안 캐시됩니다. 쿼리 결과가 캐시되면 데이터베이스에 대해 실행되지 않으며 결과는 애플리케이션에서 지정한 기본 캐시 드라이버에서 로드됩니다. 캐싱을 지원하는 드라이버를 사용하는 경우 캐시에 태그를 추가할 수도 있습니다.

코드는 다음과 같습니다.

$users = DB::table('users')-> ;cacheTags(배열 ('사람', '저자'))->remember(10)->get();


성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.