Skip to content

Commit d58cfaa

Browse files
Bakketaylorotwell
andauthored
[10.x] Adds documentation for joinLateral and leftJoinLateral (#9421)
* [10.x] Adds documentation for `joinLateral` and `leftJoinLateral` * formatting --------- Co-authored-by: Taylor Otwell <taylor@laravel.com>
1 parent d55b27a commit d58cfaa

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

queries.md

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -380,6 +380,26 @@ You may use the `joinSub`, `leftJoinSub`, and `rightJoinSub` methods to join a q
380380
$join->on('users.id', '=', 'latest_posts.user_id');
381381
})->get();
382382

383+
<a name="lateral-joins"></a>
384+
#### Lateral Joins
385+
386+
> [!WARNING]
387+
> Lateral joins are currently supported by PostgreSQL, MySQL >= 8.0.14, and SQL Server.
388+
389+
You may use the `joinLateral` and `leftJoinLateral` methods to perform a "lateral join" with a subquery. Each of these methods receives two arguments: the subquery and its table alias. The join condition(s) should be specified within the `where` clause of the given subquery. Lateral joins are evaluated for each row and can reference columns outside the subquery.
390+
391+
In this example, we will retrieve a collection of users as well as the user's three most recent blog posts. Each user can produce up to three rows in the result set: one for each of their most recent blog posts. The join condition is specified with a `whereColumn` clause within the subquery, referencing the current user row:
392+
393+
$latestPosts = DB::table('posts')
394+
->select('id as post_id', 'title as post_title', 'created_at as post_created_at')
395+
->whereColumn('user_id', 'users.id')
396+
->orderBy('created_at', 'desc')
397+
->limit(3);
398+
399+
$users = DB::table('users')
400+
->joinLateral($latestPosts, 'latest_posts')
401+
->get();
402+
383403
<a name="unions"></a>
384404
## Unions
385405

0 commit comments

Comments
 (0)