Laravel 데이터베이스: 쿼리 빌더 편집하기

경고: 로그인하지 않았습니다. 편집을 하면 IP 주소가 공개되게 됩니다. 로그인하거나 계정을 생성하면 편집자가 사용자 이름으로 기록되고, 다른 장점도 있습니다.

편집을 취소할 수 있습니다. 이 편집을 되돌리려면 아래의 바뀐 내용을 확인한 후 게시해주세요.

최신판 당신의 편집
1번째 줄: 1번째 줄:
==개요==
==개요==
{{작성중}}
{{목차숨김|3}}
[[분류: Laravel]]
;<nowiki>Database: Query Builder</nowiki>
;<nowiki>Database: Query Builder</nowiki>
;<nowiki>데이터: 쿼리 빌더</nowiki>
;<nowiki>데이터: 쿼리 빌더</nowiki>
https://laravel.com/docs/11.x/queries


==소개==
==소개==
89번째 줄: 87번째 줄:
</syntaxhighlight>
</syntaxhighlight>


결과 콜렉션이 사용할 키를 지정하려면 <code>pluck</code> 메소드의 두 번째 인수로 지정할 수 있습니다:
결과 콜렉션이 사용할 키를 지정하려면 <code>pluck</code> 메서드의 두 번째 인수로 지정할 수 있습니다:


<syntaxhighlight lang='php'>
<syntaxhighlight lang='php'>
149번째 줄: 147번째 줄:
</syntaxhighlight>
</syntaxhighlight>


마찬가지로, 검색된 레코드를 반복하면서 업데이트하려는 경우 <code>lazyById</code> 또는 <code>lazyByIdDesc</code> 메소드를 사용하는 것이 좋습니다. 이 메소드들은 레코드의 기본키를 기준으로 결과를 자동으로 페이지화합니다:
마찬가지로, 검색된 레코드를 반복하면서 업데이트하려는 경우 <code>lazyById</code> 또는 <code>lazyByIdDesc</code> 메소드를 사용하는 것이 좋습니다. 이 메서드들은 레코드의 기본키를 기준으로 결과를 자동으로 페이지화합니다:


<syntaxhighlight lang='php'>
<syntaxhighlight lang='php'>
163번째 줄: 161번째 줄:


===집계===
===집계===
쿼리 빌더는 <code>count</code>, <code>max</code>, <code>min</code>, <code>avg</code>, <code>sum</code>과 같은 집계 값을 조회하기 위한 다양한 메소드를 제공합니다. 쿼리를 작성한 후 이러한 메소드 중 하나를 호출할 수 있습니다:
<syntaxhighlight lang='php'>
use Illuminate\Support\Facades\DB;
$users = DB::table('users')->count();
$price = DB::table('orders')->max('price');
</syntaxhighlight>
물론, 이러한 메소드를 다른 절과 결합하여 집계 값을 세밀하게 조정할 수 있습니다:
<syntaxhighlight lang='php'>
$price = DB::table('orders')
                ->where('finalized', 1)
                ->avg('price');
</syntaxhighlight>
;레코드 존재 여부 확인
쿼리의 제약 조건에 맞는 레코드가 존재하는지 확인하기 위해 <code>count</code> 메소드를 사용하는 대신, <code>exists</code>와 <code>doesntExist</code> 메소드를 사용할 수 있습니다:
<syntaxhighlight lang='php'>
if (DB::table('orders')->where('finalized', 1)->exists()) {
    // ...
}
if (DB::table('orders')->where('finalized', 1)->doesntExist()) {
    // ...
}
</syntaxhighlight>
==Select 문==
;Select 절 지정하기
데이터베이스 테이블에서 모든 컬럼을 선택하고 싶지 않을 때가 있습니다. <code>select</code> 메소드를 사용하여 쿼리에 대한 커스텀 "select" 절을 지정할 수 있습니다:
<syntaxhighlight lang='php'>
use Illuminate\Support\Facades\DB;
$users = DB::table('users')
            ->select('name', 'email as user_email')
            ->get();
</syntaxhighlight>
<code>distinct</code> 메소드를 사용하면 쿼리가 고유한 결과를 반환하도록 강제할 수 있습니다:
<syntaxhighlight lang='php'>
$users = DB::table('users')->distinct()->get();
</syntaxhighlight>
이미 쿼리 빌더 인스턴스를 가지고 있고 기존 select 절에 열을 추가하려면 <code>addSelect</code> 메소드를 사용할 수 있습니다:
<syntaxhighlight lang='php'>
$query = DB::table('users')->select('name');
$users = $query->addSelect('age')->get();
</syntaxhighlight>


==문 선택==
==원시 표현==
==원시 표현==
때로는 쿼리에 임의의 문자열을 삽입해야 할 때가 있습니다. 원시 문자열 표현을 만들기 위해서는 <code>DB</code> 파사드에서 제공하는 <code>raw</code> 메소드를 사용할 수 있습니다.
<syntaxhighlight lang='php'>
$users = DB::table('users')
            ->select(DB::raw('count(*) as user_count, status'))
            ->where('status', '<>', 1)
            ->groupBy('status')
            ->get();
</syntaxhighlight>
원시 문은 문자열로 쿼리에 삽입되므로 SQL 인젝션 취약성을 피하기 위해 매우 신중해야 합니다.
;원시 메소드
<code>DB::raw</code> 메소드 대신에 다양한 쿼리의 부분에 원시 표현식을 삽입하기 위해 다음 메소드들을 사용할 수 있습니다. '''원시 표현식을 사용하는 쿼리는 SQL 인젝션 취약성으로부터 보호되지 않을 수 있음을 유의하십시오.'''
;selectRaw
<code>selectRaw</code> 메소드는 <code>addSelect(DB::raw(/* ... */))</code> 대신 사용할 수 있습니다. 이 메소드는 선택적으로 두 번째 인수로 바인딩 배열을 받습니다:
<syntaxhighlight lang='php'>
$orders = DB::table('orders')
                ->selectRaw('price * ? as price_with_tax', [1.0825])
                ->get();
</syntaxhighlight>
;where Raw / orWhereRaw
<code>whereRaw</code>와 <code>orWhereRaw</code> 메소드는 쿼리에 원시 "where" 절을 삽입하는 데 사용됩니다. 이 메소드는 선택적으로 두 번째 인수로 바인딩 배열을 받습니다:
<syntaxhighlight lang='php'>
$orders = DB::table('orders')
                ->whereRaw('price > IF(state = "TX", ?, 100)', [200])
                ->get();
</syntaxhighlight>
;havingRaw / orHavingRaw
<code>havingRaw</code>와 <code>orHavingRaw</code> 메소드는 "having" 절의 값으로 원시 문자열을 제공하는 데 사용됩니다. 이 메소드는 선택적으로 두 번째 인수로 바인딩 배열을 받습니다:
<syntaxhighlight lang='php'>
$orders = DB::table('orders')
                ->select('department', DB::raw('SUM(price) as total_sales'))
                ->groupBy('department')
                ->havingRaw('SUM(price) > ?', [2500])
                ->get();
</syntaxhighlight>
;orderByRaw
<code>orderByRaw</code> 메소드는 "order by" 절의 값으로 원시 문자열을 제공하는 데 사용됩니다:
<syntaxhighlight lang='php'>
$orders = DB::table('orders')
                ->orderByRaw('updated_at - created_at DESC')
                ->get();
</syntaxhighlight>
;groupByRaw
<code>groupByRaw</code> 메소드는 "group by" 절의 값으로 원시 문자열을 제공하는 데 사용됩니다:
<syntaxhighlight lang='php'>
$orders = DB::table('orders')
                ->select('city', 'state')
                ->groupByRaw('city, state')
                ->get();
</syntaxhighlight>
==조인==
==조인==
;내부 조인(inner join) 절
쿼리 빌더를 사용하여 쿼리에 조인 절을 추가할 수 있습니다. 기본적인 "내부 조인"을 수행하려면 쿼리 빌더 인스턴스의 <code>join</code> 메소드를 사용할 수 있습니다. <code>join</code> 메소드에 전달되는 첫 번째 인수는 조인할 테이블의 이름이며, 나머지 인수는 조인에 필요한 컬럼 제약조건을 지정합니다. 단일 쿼리에서 여러 테이블을 조인할 수도 있습니다:
<syntaxhighlight lang='php'>
use Illuminate\Support\Facades\DB;
$users = DB::table('users')
            ->join('contacts', 'users.id', '=', 'contacts.user_id')
            ->join('orders', 'users.id', '=', 'orders.user_id')
            ->select('users.*', 'contacts.phone', 'orders.price')
            ->get();
</syntaxhighlight>
;왼쪽 조인(left join) / 오른쪽 조인(right join) 절
"내부 조인" 대신 "왼쪽 조인" 또는 "오른쪽 조인"을 수행하려면 <code>leftJoin</code> 또는 <code>rightJoin</code> 메소드를 사용하세요. 이 메소드의 시그니처는 <code>join</code> 메소드와 동일합니다:
<syntaxhighlight lang='php'>
$users = DB::table('users')
            ->leftJoin('posts', 'users.id', '=', 'posts.user_id')
            ->get();
$users = DB::table('users')
            ->rightJoin('posts', 'users.id', '=', 'posts.user_id')
            ->get();
</syntaxhighlight>
;교차 조인(cross join) 절
<code>crossJoin</code> 메소드를 사용하여 "교차 조인"을 수행할 수 있습니다. 교차 조인은 첫 번째 테이블과 조인된 테이블 간의 카티전 곱을 생성합니다:
<syntaxhighlight lang='php'>
$sizes = DB::table('sizes')
            ->crossJoin('colors')
            ->get();
</syntaxhighlight>
;고급 조인 절
더 고급 조인 절을 지정할 수도 있습니다. 시작하려면, <code>join</code> 메소드의 두 번째 인수로 클로저를 전달하세요. 클로저는 <code>Illuminate\Database\Query\JoinClause</code> 인스턴스를 수신하여 "조인" 절에 대한 제약조건을 지정할 수 있습니다:
<syntaxhighlight lang='php'>
DB::table('users')
        ->join('contacts', function (JoinClause $join) {
            $join->on('users.id', '=', 'contacts.user_id')->orOn(/* ... */);
        })
        ->get();
</syntaxhighlight>
조인에 "where" 절을 사용하려면 <code>JoinClause</code> 인스턴스에서 제공하는 <code>where</code>와 <code>orWhere</code> 메소드를 사용할 수 있습니다. 이 메소드들은 두 컬럼을 비교하는 대신 컬럼을 값과 비교합니다:
<syntaxhighlight lang='php'>
DB::table('users')
        ->join('contacts', function (JoinClause $join) {
            $join->on('users.id', '=', 'contacts.user_id')
                ->where('contacts.user_id', '>', 5);
        })
        ->get();
</syntaxhighlight>
;서브쿼리 조인
<code>joinSub</code>, <code>leftJoinSub</code>, <code>rightJoinSub</code> 메소드를 사용하여 쿼리를 서브쿼리에 조인할 수 있습니다. 이 메소드 각각은 서브쿼리, 테이블 별칭, 관련 컬럼을 정의하는 클로저를 세 인수로 받습니다. 이 예제에서는 각 사용자 레코드에 사용자의 가장 최근에 게시된 블로그 게시물의 <code>created_at</code> 타임스탬프도 포함된 사용자 콜렉션을 검색합니다:
<syntaxhighlight lang='php'>
$latestPosts = DB::table('posts')
                  ->select('user_id', DB::raw('MAX(created_at) as last_post_created_at'))
                  ->where('is_published', true)
                  ->groupBy('user_id');
$users = DB::table('users')
        ->joinSub($latestPosts, 'latest_posts', function (JoinClause $join) {
            $join->on('users.id', '=', 'latest_posts.user_id');
        })->get();
</syntaxhighlight>
;래터럴 조인(lateral join)
{{WARNING}}
래터럴 조인은 현재 PostgreSQL, MySQL >= 8.0.14, SQL Server에서 지원됩니다.
{{/WARNING}}
<code>joinLateral</code>, <code>leftJoinLateral</code> 메소드를 사용하여 서브쿼리와 "래터럴 조인"을 수행할 수 있습니다. 이 메소드 각각은 두 인수, 서브쿼리와 테이블 별칭을 받습니다. 조인 조건은 주어진 서브쿼리의 <code>where</code> 절 내에 지정해야 합니다. 래터럴 조인은 각 행에 대해 평가되며 서브쿼리 외부의 컬럼을 참조할 수 있습니다.
이 예제에서는 각 사용자와 사용자의 가장 최근의 블로그 게시물 세 개를 조회합니다. 각 사용자는 결과 집합에서 최대 세 개의 행을 생성할 수 있으며, 각 행은 사용자의 가장 최근 블로그 게시물에 해당합니다. 조인 조건은 현재 사용자 행을 참조하는 서브쿼리 내의 <code>whereColumn</code> 절로 지정됩니다:
<syntaxhighlight lang='php'>
$latestPosts = DB::table('posts')
                  ->select('id as post_id', 'title as post_title', 'created_at as post_created_at')
                  ->whereColumn('user_id', 'users.id')
                  ->orderBy('created_at', 'desc')
                  ->limit(3);
$users = DB::table('users')
            ->joinLateral($latestPosts, 'latest_posts')
            ->get();
</syntaxhighlight>
==유니온==
==유니온==
==기본 Where 절==
==기본 Where 절==
474번째 줄: 255번째 줄:


===Where Any / All 절===
===Where Any / All 절===
때로는 여러 컬럼에 동일한 쿼리 제약조건을 적용해야 할 때가 있습니다. 예를 들어, 주어진 목록의 모든 컬럼이 특정 값과 <code>LIKE</code> 조건에 맞는 모든 레코드를 조회하고 싶을 수 있습니다. 이를 위해 <code>whereAny</code> 메소드를 사용할 수 있습니다:
<syntaxhighlight lang='php'>
$users = DB::table('users')
            ->where('active', true)
            ->whereAny([
                'name',
                'email',
                'phone',
            ], 'LIKE', 'Example%')
            ->get();
</syntaxhighlight>
위의 쿼리는 다음 SQL로 변환됩니다:
<syntaxhighlight lang='php'>
SELECT *
FROM users
WHERE active = true AND (
    name LIKE 'Example%' OR
    email LIKE 'Example%' OR
    phone LIKE 'Example%'
)
</syntaxhighlight>
마찬가지로, <code>whereAll</code> 메소드를 사용하여 주어진 모든 컬럼이 특정 제약조건에 맞는 레코드를 조회할 수 있습니다:
<syntaxhighlight lang='php'>
$posts = DB::table('posts')
            ->where('published', true)
            ->whereAll([
                'title',
                'content',
            ], 'LIKE', '%Laravel%')
            ->get();
</syntaxhighlight>
위의 쿼리는 다음 SQL로 변환됩니다:
<syntaxhighlight lang='sql'>
SELECT *
FROM posts
WHERE published = true AND (
    title LIKE '%Laravel%' AND
    content LIKE '%Laravel%'
)
</syntaxhighlight>
===JSON Where 절===
===JSON Where 절===
Laravel은 JSON 컬럼 유형을 지원하는 데이터베이스에서 JSON 컬럼 유형을 쿼리하는 것을 지원합니다. 현재 MySQL 8.0+, PostgreSQL 12.0+, SQL Server 2017+, SQLite 3.39.0+ ([https://www.sqlite.org/json1.html JSON1 확장] 포함)이 이에 해당합니다. JSON 컬럼을 쿼리하려면 <code>-></code> 연산자를 사용하세요:
Laravel은 JSON 컬럼 유형을 지원하는 데이터베이스에서 JSON 컬럼 유형을 쿼리하는 것을 지원합니다. 현재 MySQL 8.0+, PostgreSQL 12.0+, SQL Server 2017+, SQLite 3.39.0+ ([https://www.sqlite.org/json1.html JSON1 확장] 포함)이 이에 해당합니다. JSON 컬럼을 쿼리하려면 <code>-></code> 연산자를 사용하세요:
796번째 줄: 529번째 줄:
==비관적 락==
==비관적 락==
==디버깅==
==디버깅==
==참고==
* https://laravel.com/docs/11.x/queries
[[분류: Laravel 쿼리빌더]]

제타위키에서의 모든 기여는 크리에이티브 커먼즈 저작자표시-동일조건변경허락 3.0 라이선스로 배포된다는 점을 유의해 주세요(자세한 내용에 대해서는 제타위키:저작권 문서를 읽어주세요). 만약 여기에 동의하지 않는다면 문서를 저장하지 말아 주세요.
또한, 직접 작성했거나 퍼블릭 도메인과 같은 자유 문서에서 가져왔다는 것을 보증해야 합니다. 저작권이 있는 내용을 허가 없이 저장하지 마세요!

취소 편집 도움말 (새 창에서 열림)