Skip to content

Commit 0add21c

Browse files
author
Pooya Parsa
committed
model relations
1 parent 72cd1f1 commit 0add21c

File tree

2 files changed

+15
-4
lines changed

2 files changed

+15
-4
lines changed

src/Jenssegers/Mongodb/Eloquent/Model.php

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@
88
use Jenssegers\Mongodb\Relations\EmbedsMany;
99
use Jenssegers\Mongodb\Relations\EmbedsOne;
1010
use Jenssegers\Mongodb\Relations\EmbedsOneOrMany;
11-
use Jenssegers\Mongodb\Relations\MorphTo;
1211
use MongoDB\BSON\ObjectID;
1312
use MongoDB\BSON\UTCDateTime;
1413
use ReflectionMethod;
@@ -234,7 +233,19 @@ public function getAttribute($key)
234233

235234
// This attribute matches an embedsOne or embedsMany relation so we need
236235
// to return the relation results instead of the interal attributes.
237-
if ($relations instanceof EmbedsOneOrMany or $relations instanceof MorphTo) {
236+
if ($relations instanceof EmbedsOneOrMany) {
237+
// If the key already exists in the relationships array, it just means the
238+
// relationship has already been loaded, so we'll just return it out of
239+
// here because there is no need to query within the relations twice.
240+
if (array_key_exists($key, $this->relations)) {
241+
return $this->relations[$key];
242+
}
243+
244+
// Get the relation results.
245+
return $this->getRelationshipFromMethod($key, $camelKey);
246+
}
247+
248+
if ($relations instanceof Relation) {
238249
// If the key already exists in the relationships array, it just means the
239250
// relationship has already been loaded, so we'll just return it out of
240251
// here because there is no need to query within the relations twice.

tests/RelationsTest.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -322,8 +322,8 @@ public function testBelongsToManyCustom()
322322
$this->assertTrue(array_key_exists('groups', $user->getAttributes()));
323323

324324
// Assert they are attached
325-
$this->assertTrue(in_array($group->_id, $user->groups));
326-
$this->assertTrue(in_array($user->_id, $group->users));
325+
$this->assertTrue(in_array($group->_id, $user->groups->pluck('_id')->toArray()));
326+
$this->assertTrue(in_array($user->_id, $group->users->pluck('_id')->toArray()));
327327
$this->assertEquals($group->_id, $user->groups()->first()->_id);
328328
$this->assertEquals($user->_id, $group->users()->first()->_id);
329329
}

0 commit comments

Comments
 (0)