최신판 |
당신의 편집 |
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'> |
232번째 줄: |
230번째 줄: |
|
| |
|
| 원시 문은 문자열로 쿼리에 삽입되므로 SQL 인젝션 취약성을 피하기 위해 매우 신중해야 합니다. | | 원시 문은 문자열로 쿼리에 삽입되므로 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번째 줄: |
322번째 줄: |
|
| |
|
| ===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번째 줄: |
596번째 줄: |
| ==비관적 락== | | ==비관적 락== |
| ==디버깅== | | ==디버깅== |
| | ==참고== |
| | * https://laravel.com/docs/11.x/queries |
| | |
| | [[분류: Laravel 쿼리빌더]] |