Skip to content

Commit

Permalink
Allows serializing union() from Query Builder instance (#10)
Browse files Browse the repository at this point in the history
  • Loading branch information
faisuc committed Jul 26, 2022
1 parent 5e18b54 commit b2ac587
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
16 changes: 15 additions & 1 deletion src/Query.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,13 @@ public static function serialize(FluentQueryBuilder $builder): array
'orders' => $builder->orders,
'limit' => $builder->limit,
'offset' => $builder->offset,
'unions' => $builder->unions,
'unions' => collect($builder->unions)->map(static function ($union) {
if (isset($union['query'])) {
$union['query'] = static::serialize($union['query']);
}

return $union;
})->all(),
'unionLimit' => $builder->unionLimit,
'unionOrders' => $builder->unionOrders,
'lock' => $builder->lock,
Expand Down Expand Up @@ -73,6 +79,14 @@ public static function unserializeFor(FluentQueryBuilder $builder, array $payloa
}
}

if ($type === 'unions') {
foreach ($value as $index => $union) {
if (isset($union['query']) && \is_array($union['query'])) {
$value[$index]['query'] = static::unserialize($union['query']);
}
}
}

if ($type === 'joins') {
$value = JoinClause::unserialize($builder, $value ?? []);
}
Expand Down
16 changes: 16 additions & 0 deletions tests/Feature/QueryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,4 +48,20 @@ public function it_can_serialize_a_basic_query_builder_with_wheres()

$this->assertSame($builder->toSql(), $unserialize->toSql());
}

/** @test */
public function it_can_serialize_a_basic_query_builder_with_unions()
{
$builder = DB::table('users')->where('email', '=', '[email protected]');
$union = DB::table('users')->where('email', '=', '[email protected]')
->union($builder);

$serialized = serialize($union);

$unserialize = unserialize($serialized);

$this->assertSame('select * from (select * from "users" where "email" = ?) union select * from (select * from "users" where "email" = ?)', $unserialize->toSql());

$this->assertSame($union->toSql(), $unserialize->toSql());
}
}

0 comments on commit b2ac587

Please sign in to comment.