Skip to content

UNION clause

Marijn van Wezel edited this page Dec 15, 2022 · 1 revision

The UNION clause is used to combine the result of multiple queries.

Query::union(callable|Query $queryOrCallable, bool $all = false): Query

Parameters

  • $queryOrCallable : The callable decorating a fresh query instance or the query instance to be attached after the union clause.
  • $all : Whether the union should include all results or remove the duplicates instead.

Relevant methods

  • setAll(bool $all = true): self : Set whether the union should include all results, instead of removing duplicates.

Examples

Combine two queries and retain duplicates

$actor = node('Actor');
$movie = node('Movie');

$query = query()
    ->match($actor)
    ->returning($actor->property('name')->alias('name'))
    ->union(
        query()
            ->match($movie)
            ->returning($movie->property('title')->alias('name')),
        true
    )
    ->build();

$this->assertStringMatchesFormat("MATCH (%s:Actor) RETURN %s.name AS name UNION ALL MATCH (%s:Movie) RETURN %s.title AS name", $query);

Combine two queries and remove duplicates

$actor = node('Actor');
$movie = node('Movie');

$query = query()
    ->match($actor)
    ->returning($actor->property('name')->alias('name'))
    ->union(
        query()
            ->match($movie)
            ->returning($movie->property('title')->alias('name'))
    )
    ->build();

$this->assertStringMatchesFormat("MATCH (%s:Actor) RETURN %s.name AS name UNION MATCH (%s:Movie) RETURN %s.title AS name", $query);

External links