Skip to content

Instantly share code, notes, and snippets.

@hotmeteor
Last active October 16, 2020 20:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hotmeteor/9c95afd9f9c36567a2c3008bc7ccd20b to your computer and use it in GitHub Desktop.
Save hotmeteor/9c95afd9f9c36567a2c3008bc7ccd20b to your computer and use it in GitHub Desktop.
<?php
$results = DB::table('users')
->select('users.id', 'users.first_name', 'users.last_name', 'users.email')
->select('latest_account.name', 'latest_account.city')
->joinLateral(function($query) {
$query->select('accounts.name', 'accounts.city')
->from('accounts')
->whereColumn('accounts.user_id', 'users.id')
->orderByDesc('accounts.id')
->limit(1);
}, 'latest_account')
->orderBy('users.last_name')
->get()
<?php
use Illuminate\Database\Query\Builder;
use Illuminate\Database\Query\Expression;
Builder::macro('joinLateral', function ($query, $as, $type = 'inner', $where = false) {
[$query, $bindings] = $this->createSub($query);
$expression = 'lateral ('.$query.') as '.$this->grammar->wrap($as);
$this->addBinding($bindings, 'join');
return $this->join(new Expression($expression), DB::raw('1'), '=', DB::raw('1'), $type, $where);
});
Builder::macro('leftJoinLateral', function ($query, $as, $where = false) {
return $this->joinLateral($query, $as, 'left', $where);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment