Skip to content

Commit

Permalink
Add crossJoinSub method to the query builder (#34400)
Browse files Browse the repository at this point in the history
Co-authored-by: Maikel van Maurik <maikel@ttc.media>
  • Loading branch information
maikelvanmaurik and Maikel van Maurik authored Sep 18, 2020
1 parent 5f78c90 commit 0151e10
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
20 changes: 20 additions & 0 deletions src/Illuminate/Database/Query/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -618,6 +618,26 @@ public function crossJoin($table, $first = null, $operator = null, $second = nul
return $this;
}

/**
* Add a subquery cross join to the query.
*
* @param \Closure|\Illuminate\Database\Query\Builder|string $query
* @param string $as
* @return $this
*/
public function crossJoinSub($query, $as)
{
[$query, $bindings] = $this->createSub($query);

$expression = '('.$query.') as '.$this->grammar->wrapTable($as);

$this->addBinding($bindings, 'join');

$this->joins[] = $this->newJoinClause($this, 'cross', new Expression($expression));

return $this;
}

/**
* Get a new join clause.
*
Expand Down
7 changes: 7 additions & 0 deletions tests/Database/DatabaseQueryBuilderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1502,6 +1502,13 @@ public function testCrossJoins()
$this->assertSame('select * from "tableB" cross join "tableA" on "tableA"."column1" = "tableB"."column2"', $builder->toSql());
}

public function testCrossJoinSubs()
{
$builder = $this->getBuilder();
$builder->selectRaw('(sale / overall.sales) * 100 AS percent_of_total')->from('sales')->crossJoinSub($this->getBuilder()->selectRaw('SUM(sale) AS sales')->from('sales'), 'overall');
$this->assertSame('select (sale / overall.sales) * 100 AS percent_of_total from "sales" cross join (select SUM(sale) AS sales from "sales") as "overall"', $builder->toSql());
}

public function testComplexJoin()
{
$builder = $this->getBuilder();
Expand Down

0 comments on commit 0151e10

Please sign in to comment.