Skip to content

Commit cb3dacc

Browse files
Load embedded relations automatically only when they are retrieved from the database
1 parent d7d1962 commit cb3dacc

File tree

2 files changed

+32
-17
lines changed

2 files changed

+32
-17
lines changed

src/Eloquent/DocumentModel.php

Lines changed: 0 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -754,20 +754,4 @@ public function refresh()
754754

755755
return $this;
756756
}
757-
758-
/** @inheritDoc */
759-
public function toArray()
760-
{
761-
$embeds = [];
762-
763-
foreach (array_keys($this->getAttributes()) as $key) {
764-
if ($this->isEmbedRelation($key)) {
765-
$embeds[] = $key;
766-
}
767-
}
768-
769-
$this->loadMissing($embeds);
770-
771-
return parent::toArray();
772-
}
773757
}

src/Eloquent/EmbedsRelations.php

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,13 @@
44

55
namespace MongoDB\Laravel\Eloquent;
66

7+
use Illuminate\Database\Eloquent\Model;
78
use Illuminate\Support\Str;
89
use MongoDB\Laravel\Relations\EmbedsMany;
910
use MongoDB\Laravel\Relations\EmbedsOne;
1011
use MongoDB\Laravel\Relations\EmbedsOneOrMany;
1112

13+
use function array_keys;
1214
use function class_basename;
1315
use function debug_backtrace;
1416
use function is_a;
@@ -20,6 +22,13 @@
2022
*/
2123
trait EmbedsRelations
2224
{
25+
public static function bootEmbedsRelations(): void
26+
{
27+
static::retrieved(function (self $model) {
28+
$model->withEmbedded();
29+
});
30+
}
31+
2332
/**
2433
* Define an embedded one-to-many relationship.
2534
*
@@ -88,14 +97,36 @@ protected function embedsOne($related, $localKey = null, $foreignKey = null, $re
8897
return new EmbedsOne($query, $this, $instance, $localKey, $foreignKey, $relation);
8998
}
9099

100+
/**
101+
* Load embedded relations on the model if they are not already loaded
102+
*
103+
* @param array|string $relations
104+
*
105+
* @return Model
106+
*/
107+
public function withEmbedded($relations = [])
108+
{
109+
if (empty($relations)) {
110+
$relations = [];
111+
112+
foreach (array_keys($this->getAttributes()) as $key) {
113+
if ($this->isEmbeddedRelation($key)) {
114+
$relations[] = $key;
115+
}
116+
}
117+
}
118+
119+
return $this->loadMissing($relations);
120+
}
121+
91122
/**
92123
* Determine if the given key is an embed relationship method on the model.
93124
*
94125
* @param string $key
95126
*
96127
* @return bool
97128
*/
98-
public function isEmbedRelation($key)
129+
public function isEmbeddedRelation($key)
99130
{
100131
return $this->isRelation($key)
101132
&& is_a($this->{$key}(), EmbedsOneOrMany::class, true);

0 commit comments

Comments
 (0)