최신판 |
당신의 편집 |
291번째 줄: |
291번째 줄: |
|
| |
|
| ==조인== | | ==조인== |
| ;내부 조인(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번째 줄: |
381번째 줄: |
|
| |
|
| ===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> 연산자를 사용하세요:
| |
|
| |
| <syntaxhighlight lang='php'>
| |
| $users = DB::table('users')
| |
| ->where('preferences->dining->meal', 'salad')
| |
| ->get();
| |
| </syntaxhighlight>
| |
|
| |
| JSON 배열을 쿼리하려면 <code>whereJsonContains</code>를 사용할 수 있습니다:
| |
|
| |
| <syntaxhighlight lang='php'>
| |
| $users = DB::table('users')
| |
| ->whereJsonContains('options->languages', 'en')
| |
| ->get();
| |
| </syntaxhighlight>
| |
|
| |
| MySQL 또는 PostgreSQL 데이터베이스를 사용하는 경우, <code>whereJsonContains</code> 메소드에 값을 배열로 전달할 수 있습니다:
| |
|
| |
| <syntaxhighlight lang='php'>
| |
| $users = DB::table('users')
| |
| ->whereJsonContains('options->languages', ['en', 'de'])
| |
| ->get();
| |
| </syntaxhighlight>
| |
|
| |
| JSON 배열의 길이를 기준으로 쿼리하려면 <code>whereJsonLength</code> 메소드를 사용할 수 있습니다:
| |
|
| |
| <syntaxhighlight lang='php'>
| |
| $users = DB::table('users')
| |
| ->whereJsonLength('options->languages', 0)
| |
| ->get();
| |
|
| |
| $users = DB::table('users')
| |
| ->whereJsonLength('options->languages', '>', 1)
| |
| ->get();
| |
| </syntaxhighlight>
| |
|
| |
| ===추가 Where 절=== | | ===추가 Where 절=== |
| ;whereBetween / orWhereBetween | | ;whereBetween / orWhereBetween |