Skip to content

[Fix] embed relations serialization #3410

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 6 commits into
base: 5.x
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions src/Eloquent/DocumentModel.php
Original file line number Diff line number Diff line change
Expand Up @@ -754,4 +754,20 @@ public function refresh()

return $this;
}

/** @inheritDoc */
public function toArray()
{
$embeds = [];

foreach (array_keys($this->getAttributes()) as $key) {
if ($this->isEmbedRelation($key)) {
$embeds[] = $key;
}
}

$this->loadMissing($embeds);

return parent::toArray();
}
}
15 changes: 15 additions & 0 deletions src/Eloquent/EmbedsRelations.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,11 @@
use Illuminate\Support\Str;
use MongoDB\Laravel\Relations\EmbedsMany;
use MongoDB\Laravel\Relations\EmbedsOne;
use MongoDB\Laravel\Relations\EmbedsOneOrMany;

use function class_basename;
use function debug_backtrace;
use function is_a;

use const DEBUG_BACKTRACE_IGNORE_ARGS;

Expand Down Expand Up @@ -85,4 +87,17 @@ protected function embedsOne($related, $localKey = null, $foreignKey = null, $re

return new EmbedsOne($query, $this, $instance, $localKey, $foreignKey, $relation);
}

/**
* Determine if the given key is an embed relationship method on the model.
*
* @param string $key
*
* @return bool
*/
public function isEmbedRelation($key)
{
return $this->isRelation($key)
&& is_a($this->{$key}(), EmbedsOneOrMany::class, true);
}
}
14 changes: 14 additions & 0 deletions tests/EmbeddedRelationsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -972,4 +972,18 @@ public function testUnsetPropertyOnEmbed()
$this->assertNull($user->addresses->get(0)->city);
$this->assertSame('Kyoto', $user->addresses->get(1)->city);
}

public function testEmbedManyToArrayCast()
{
$user = User::create(['name' => 'John Doe']);
$user->addresses()->saveMany([new Address(['city' => 'London'])]);

//Reload document
$user = User::where('name', 'John Doe')->first();
$array = $user->toArray();

$this->assertIsString($array['addresses'][0]['id']);
$this->assertIsString($array['addresses'][0]['created_at']);
$this->assertIsString($array['addresses'][0]['updated_at']);
}
}
Loading