Skip to content

Commit b2ac587

Browse files
authored
Allows serializing union() from Query Builder instance (#10)
1 parent 5e18b54 commit b2ac587

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

src/Query.php

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,13 @@ public static function serialize(FluentQueryBuilder $builder): array
3838
'orders' => $builder->orders,
3939
'limit' => $builder->limit,
4040
'offset' => $builder->offset,
41-
'unions' => $builder->unions,
41+
'unions' => collect($builder->unions)->map(static function ($union) {
42+
if (isset($union['query'])) {
43+
$union['query'] = static::serialize($union['query']);
44+
}
45+
46+
return $union;
47+
})->all(),
4248
'unionLimit' => $builder->unionLimit,
4349
'unionOrders' => $builder->unionOrders,
4450
'lock' => $builder->lock,
@@ -73,6 +79,14 @@ public static function unserializeFor(FluentQueryBuilder $builder, array $payloa
7379
}
7480
}
7581

82+
if ($type === 'unions') {
83+
foreach ($value as $index => $union) {
84+
if (isset($union['query']) && \is_array($union['query'])) {
85+
$value[$index]['query'] = static::unserialize($union['query']);
86+
}
87+
}
88+
}
89+
7690
if ($type === 'joins') {
7791
$value = JoinClause::unserialize($builder, $value ?? []);
7892
}

tests/Feature/QueryTest.php

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,4 +48,20 @@ public function it_can_serialize_a_basic_query_builder_with_wheres()
4848

4949
$this->assertSame($builder->toSql(), $unserialize->toSql());
5050
}
51+
52+
/** @test */
53+
public function it_can_serialize_a_basic_query_builder_with_unions()
54+
{
55+
$builder = DB::table('users')->where('email', '=', 'crynobone@gmail.com');
56+
$union = DB::table('users')->where('email', '=', 'johndoe@gmail.com')
57+
->union($builder);
58+
59+
$serialized = serialize($union);
60+
61+
$unserialize = unserialize($serialized);
62+
63+
$this->assertSame('select * from (select * from "users" where "email" = ?) union select * from (select * from "users" where "email" = ?)', $unserialize->toSql());
64+
65+
$this->assertSame($union->toSql(), $unserialize->toSql());
66+
}
5167
}

0 commit comments

Comments
 (0)