Skip to content

Commit 0151e10

Browse files
maikelvanmaurikMaikel van Maurik
andauthored
Add crossJoinSub method to the query builder (#34400)
Co-authored-by: Maikel van Maurik <[email protected]>
1 parent 5f78c90 commit 0151e10

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

src/Illuminate/Database/Query/Builder.php

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -618,6 +618,26 @@ public function crossJoin($table, $first = null, $operator = null, $second = nul
618618
return $this;
619619
}
620620

621+
/**
622+
* Add a subquery cross join to the query.
623+
*
624+
* @param \Closure|\Illuminate\Database\Query\Builder|string $query
625+
* @param string $as
626+
* @return $this
627+
*/
628+
public function crossJoinSub($query, $as)
629+
{
630+
[$query, $bindings] = $this->createSub($query);
631+
632+
$expression = '('.$query.') as '.$this->grammar->wrapTable($as);
633+
634+
$this->addBinding($bindings, 'join');
635+
636+
$this->joins[] = $this->newJoinClause($this, 'cross', new Expression($expression));
637+
638+
return $this;
639+
}
640+
621641
/**
622642
* Get a new join clause.
623643
*

tests/Database/DatabaseQueryBuilderTest.php

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1502,6 +1502,13 @@ public function testCrossJoins()
15021502
$this->assertSame('select * from "tableB" cross join "tableA" on "tableA"."column1" = "tableB"."column2"', $builder->toSql());
15031503
}
15041504

1505+
public function testCrossJoinSubs()
1506+
{
1507+
$builder = $this->getBuilder();
1508+
$builder->selectRaw('(sale / overall.sales) * 100 AS percent_of_total')->from('sales')->crossJoinSub($this->getBuilder()->selectRaw('SUM(sale) AS sales')->from('sales'), 'overall');
1509+
$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());
1510+
}
1511+
15051512
public function testComplexJoin()
15061513
{
15071514
$builder = $this->getBuilder();

0 commit comments

Comments
 (0)