Skip to content

Commit 36a9bf8

Browse files
committed
Fix missing linkage for empty to-many relationships
1 parent 11fafff commit 36a9bf8

File tree

2 files changed

+33
-2
lines changed

2 files changed

+33
-2
lines changed

src/Schema/Field/ToMany.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,13 +18,13 @@ public function serializeValue($value, Context $context): mixed
1818
{
1919
$meta = $this->serializeMeta($context);
2020

21-
if ((($context->include === null && !$this->linkage) || !$value) && !$meta) {
21+
if ((($context->include === null && !$this->linkage) || $value === null) && !$meta) {
2222
return null;
2323
}
2424

2525
$relationship = [];
2626

27-
if ($value) {
27+
if ($value !== null) {
2828
$relationship['data'] = array_map(
2929
fn($model) => $context->serializer->addIncluded($this, $model, $context->include),
3030
$value,

tests/feature/RelationshipToManyTest.php

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,37 @@ public function test_to_many_with_linkage()
6060
);
6161
}
6262

63+
public function test_empty_to_many_with_linkage()
64+
{
65+
$this->api->resource(
66+
new MockResource(
67+
'users',
68+
models: [(object) ['id' => '3', 'friends' => []]],
69+
endpoints: [Show::make()],
70+
fields: [
71+
ToMany::make('friends')
72+
->withLinkage()
73+
->type('users'),
74+
],
75+
),
76+
);
77+
78+
$response = $this->api->handle($this->buildRequest('GET', '/users/3'));
79+
80+
$this->assertJsonApiDocumentSubset(
81+
[
82+
'data' => [
83+
'type' => 'users',
84+
'id' => '3',
85+
'relationships' => [
86+
'friends' => ['data' => []],
87+
],
88+
],
89+
],
90+
$response->getBody(),
91+
);
92+
}
93+
6394
public function test_to_many_without_linkage()
6495
{
6596
$this->api->resource(

0 commit comments

Comments
 (0)