|
4 | 4 |
|
5 | 5 | namespace MongoDB\Laravel\Eloquent;
|
6 | 6 |
|
| 7 | +use Illuminate\Database\Eloquent\Model; |
7 | 8 | use Illuminate\Support\Str;
|
8 | 9 | use MongoDB\Laravel\Relations\EmbedsMany;
|
9 | 10 | use MongoDB\Laravel\Relations\EmbedsOne;
|
10 | 11 | use MongoDB\Laravel\Relations\EmbedsOneOrMany;
|
11 | 12 |
|
| 13 | +use function array_keys; |
12 | 14 | use function class_basename;
|
13 | 15 | use function debug_backtrace;
|
14 | 16 | use function is_a;
|
|
20 | 22 | */
|
21 | 23 | trait EmbedsRelations
|
22 | 24 | {
|
| 25 | + public static function bootEmbedsRelations(): void |
| 26 | + { |
| 27 | + static::retrieved(function (self $model) { |
| 28 | + $model->withEmbedded(); |
| 29 | + }); |
| 30 | + } |
| 31 | + |
23 | 32 | /**
|
24 | 33 | * Define an embedded one-to-many relationship.
|
25 | 34 | *
|
@@ -88,14 +97,36 @@ protected function embedsOne($related, $localKey = null, $foreignKey = null, $re
|
88 | 97 | return new EmbedsOne($query, $this, $instance, $localKey, $foreignKey, $relation);
|
89 | 98 | }
|
90 | 99 |
|
| 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 | + |
91 | 122 | /**
|
92 | 123 | * Determine if the given key is an embed relationship method on the model.
|
93 | 124 | *
|
94 | 125 | * @param string $key
|
95 | 126 | *
|
96 | 127 | * @return bool
|
97 | 128 | */
|
98 |
| - public function isEmbedRelation($key) |
| 129 | + public function isEmbeddedRelation($key) |
99 | 130 | {
|
100 | 131 | return $this->isRelation($key)
|
101 | 132 | && is_a($this->{$key}(), EmbedsOneOrMany::class, true);
|
|
0 commit comments